Android 中数据加密 ---- RSA加密

前言:

对于RSA加密,在博文  RSA 加密 已经有了详细说明,这边博文将其用Android 实现。

 

更多的加密可以看:

数据加密 ---- 总篇

Android 中数据加密 ---- 异或加密

Android 中数据加密 ---- AES加密

Android 中数据加密 ---- DES加密

Android 中数据加密 ---- 3DES加密

Android 中数据加密 ---- MD5加密

Android 中数据加密 ---- SHA加密

 

实例:

实现的详细代码同 AES 加密的实例,这里将抽象的几个接口实现类RSAEncryption 贴出来:

public class RSAEncryption extends BlockEncryption {
    private static final String ALGORITHM = "RSA";
    private static final String PADDING = "/ECB/PKCS1Padding";
    private static final int DEFAULT_KEY_SIZE = 1024;

    private static final int RSA_BLOCK_SIZE = 11;

    public static final int TYPE_ENCRYPTION_WITH_PUBLIC = 0;
    public static final int TYPE_ENCRYPTION_WITH_PRIVATE = 1;

    private int mEncryptionType = TYPE_ENCRYPTION_WITH_PUBLIC;

    private int mKeyLength = DEFAULT_KEY_SIZE;
    private PublicKey mPublicKey;
    private PrivateKey mPrivateKey;

    public RSAEncryption() {
    }

    public void setEncryptionType(int type) {
        mEncryptionType = type;
    }

    public void setKeyLength(int keyLength) {
        mKeyLength = keyLength;
    }

    private KeyPair generateRSAKeyPair(int keyLength) {
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM);
            kpg.initialize(keyLength);
            return kpg.genKeyPair();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void generateKeys() {
        KeyPair keyPair = generateRSAKeyPair(mKeyLength);

        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        try {
            // get public key
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey.getEncoded());
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM);
            mPublicKey = kf.generatePublic(keySpec);

            // get private key
            PKCS8EncodedKeySpec keySpec1 = new PKCS8EncodedKeySpec(privateKey.getEncoded());
            mPrivateKey = kf.generatePrivate(keySpec1);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private Key getKey(int mode) {
        if (mEncryptionType == TYPE_ENCRYPTION_WITH_PRIVATE) {
            return mode == Cipher.ENCRYPT_MODE ? mPrivateKey : mPublicKey;
        }
        return mode == Cipher.ENCRYPT_MODE ? mPublicKey : mPrivateKey;
    }

    @Override
    public Cipher getCipher(int mode) {
        if (mode != Cipher.ENCRYPT_MODE && mode != Cipher.DECRYPT_MODE)
            return null;

        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM + PADDING);
            cipher.init(mode, getKey(mode));
            return cipher;
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public String getAlgorithm() {
        return ALGORITHM;
    }

    @Override
    protected int getBlockSize() {
        return RSA_BLOCK_SIZE;
    }

    @Override
    protected int getBufferSize() {
        return (mKeyLength / 8) - RSA_BLOCK_SIZE;
    }

}

需要注意的是,这里的buffer size 为key length/8,block size 是11。

另外,因为RSA 需要public key 和private key,所以gitCipher() 不再使用BlockEncryptionHelper 中的方法。

 

Activity 中设置button 进行点击:

    private void testEncryptionRSA() {
        Button ersa = (Button) findViewById(R.id.encrypt_rsa);
        ersa.setOnClickListener(this);

        Button drsa = (Button) findViewById(R.id.decrypt_rsa);
        drsa.setOnClickListener(this);
    }

    private void rsaEncryption() {
        {
            mOperationTitle.setText(getString(R.string.encrypt_rsa));
            String strSource = "hliuhiufhliuhsd;jfijso;goshgosjogijsgo;j";
            mBeforeOperation.setText(getString(R.string.before_operation, strSource));

            if (mRSAEncryption == null) {
                mRSAEncryption = new RSAEncryption();
                mRSAEncryption.generateKeys();
            }

            mStrEncrypted = mRSAEncryption.strEncryption(strSource);
            Log.d(TAG, "==== mStrEncrypted = " + mStrEncrypted);
            mAfterOperation.setText(getString(R.string.after_operation, mStrEncrypted));
        }

//        if (mFileEncryption != null) {
//            Log.d(TAG, "==== test file, encryption with rsa ...");
//            String filePath = "/storage/emulated/0/hehe.png";
//            String destPath = "/storage/emulated/0/2.png";
//            mFileEncryption.setAlgorithm(FileEncryption.ALG_MODE_RSA);
//            mFileEncryption.start(FileEncryption.MODE_ENCRYPT, filePath, destPath);
//            Log.d(TAG, "==== test file, encryption end");
//        }
    }

    private void rsaDecryption() {
        {
            mOperationTitle.setText(getString(R.string.decrypt_rsa));
            mBeforeOperation.setText(getString(R.string.before_operation, mStrEncrypted));

            if (mRSAEncryption == null) {
                mRSAEncryption = new RSAEncryption();
                mRSAEncryption.generateKeys();
            }

            String strDecrypted = mRSAEncryption.strDecryption(mStrEncrypted);
            Log.d(TAG, "==== strDecrypted = " + strDecrypted);
            mAfterOperation.setText(getString(R.string.after_operation, strDecrypted));
        }

//        if (mFileEncryption != null) {
//            Log.d(TAG, "==== test file, decryption with rsa ...");
//            String filePath = "/storage/emulated/0/hehe.png";
//            String destPath = "/storage/emulated/0/2.png";
//            mFileEncryption.setAlgorithm(FileEncryption.ALG_MODE_RSA);
//            mFileEncryption.start(FileEncryption.MODE_DECRYPT, destPath, filePath);
//            Log.d(TAG, "==== test file, decryption end");
//        }
    }

注释掉的是对于文件的加密、解密,同样是实用的。

 

结果:

12-19 05:04:19.186  1958  1958 D TestEncryptionActivity: ==== mStrEncrypted = kPSmTWshnnFvHxOgxgp/qL7cJ2jHwx7sz+DE4cjrmskgeHOc1BKdBJGmKPTMN2JvY5NwI7Od5s/1
12-19 05:04:19.186  1958  1958 D TestEncryptionActivity: gNJX4Bzad/gvUgskpWklFOTHtfQL9hS1aG67fPhG8YXrbyOiHDYFSRxNdEFxRla4CkNRx+DDUWq7
12-19 05:04:19.186  1958  1958 D TestEncryptionActivity: /zDqAkA92myhgMUCLKk=
12-19 05:04:24.587  1958  1958 D TestEncryptionActivity: ==== strDecrypted = hliuhiufhliuhsd;jfijso;goshgosjogijsgo;j
12-19 05:04:32.139  1958  1958 D TestEncryptionActivity: ==== mStrEncrypted = PgZyrAPsJNIwa1sXSpeRFe5z8XsNHMJ0sPsNmLycdHKO4kZhiOWAvfXjMgaN2r6exhWLMbkzY+Kw
12-19 05:04:32.139  1958  1958 D TestEncryptionActivity: dGV8KHdVYWdy6GVUXGa85lPYkuEtGKyDXdAX8erXYhKdwGGKPcZtqFK074K0R7p1inFy2g24LEkl
12-19 05:04:32.139  1958  1958 D TestEncryptionActivity: RyMAZwuRCjgPiDJTqw4=
12-19 05:04:34.194  1958  1958 D TestEncryptionActivity: ==== strDecrypted = hliuhiufhliuhsd;jfijso;goshgosjogijsgo;j
12-19 05:04:35.797  1958  1958 D TestEncryptionActivity: ==== mStrEncrypted = EaFez+qztG8VP1WmgUaAdeQp7ZbuC0p+JwKiHYpo3VymgZ6fV4Yc4+Wfm64D4AQKPONzSVm7q8fc
12-19 05:04:35.797  1958  1958 D TestEncryptionActivity: fd4nnAfk+wqDYYyStvg+4D4LGvEXe6UZaKXw9leqfR9bLiSazbUgVzD60TwDE8Sgbx/igeoSX40G
12-19 05:04:35.797  1958  1958 D TestEncryptionActivity: 30MbOgVbjfQN3gRR86Q=
12-19 05:04:37.150  1958  1958 D TestEncryptionActivity: ==== strDecrypted = hliuhiufhliuhsd;jfijso;goshgosjogijsgo;j

每一次加密的结果都不一样,这个是因为加密的key 是public key,所以填充都会随机变化,导致了最后结果的不同。

如果加密的时候为private key,那么加密后的值是相同的。

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
RSA封装类 ,完整的RSA加密和解密 public class RSAUtilEncrypt { public static final String KEY_ALGORTHM = "RSA";// public static final String KEY_ALGORTHM_RSA_ECB_PKCS1PADDING = "RSA/ECB/PKCS1Padding"; public static String RSA_PUBLIC_KEY = "rsa_public_key"; public static String RSA_PRIVATE_KEY = "rsa_private_key"; private int KeySize = 1024; private Map keyMap; private static String RSA = "RSA"; private static PublicKey publickey; public RSAUtilEncrypt(int KeySize,String publickey) { this.KeySize = KeySize; try { this.publickey=generatePublicKeyByString(publickey); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private RSAPublicKey generatePublicKeyByString(String publicKeyStr) throws Exception { try { BASE64Decoder base64Decoder = new BASE64Decoder(); byte[] buffer = base64Decoder.decodeBuffer(publicKeyStr); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return (RSAPublicKey) keyFactory.generatePublic(keySpec); } catch (NoSuchAlgorithmException e) { throw new Exception("No Algorthm,Checked by cemung!"); } catch (InvalidKeySpecException e) { throw new Exception("InvalidKeySpec!"); } catch (IOException e) { throw new Exception("Io exception!"); } catch (NullPointerException e) { throw new Exception("Illegle pointer reference!"); } } // Encypt public byte[] RSAEncrypt(byte[] data, RSAPublicKey publickey) throws Exception { Cipher cipher = Cipher.getInstance(KEY_ALGORTHM_RSA_ECB_PKCS1PADDING); cipher.init(Cipher.ENCRYPT_MODE, this.publickey); byte[] cipherbytes = cipher.doFinal(data); return cipherbytes; } // Encypt public byte[] RSAEncrypt(byte[] data) throws Exception { Cipher cipher = Cipher.getInstance(KEY_ALGORTHM_RSA_ECB_PKCS1PADDING); cipher.init(Cipher.ENCRYPT_MODE, this.publickey); byte[] cipherbytes = cipher.doFinal(data); return cipherbytes; } // Get Public key with format byte[] public byte[] getPublicKeyByte() { RSAPublicKey pubkey = (RSAPublicKey) keyMap.get(RSA_PUBLIC_KEY); return pubkey.getEncoded(); } public static byte[] decryptBASE64(String key) throws Exception { return (new BASE64Decoder()).decodeBuffer(key); } public static String encryptBASE64(byte[] key) throws Exception { return (new BASE64Encoder()).encodeBuffer(key); } public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception { byte[] keyBytes = decryptBASE64(key); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec( keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(data); } public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception { byte[] keyBytes = decryptBASE64(key); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(data); } public static byte[] decryptByPublicKey(byte[] data, String key) throws Exception { byte[] keyBytes = decryptBASE64(key); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM); Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicKey); return cipher.doFinal(data); } 使用方法 private RSAUtilEncrypt rsa = new RSAUtilEncrypt(1024, publikey); /* * 给信息加密,获取密文 */ public String getCiphertext(String str_encrode) { try { byte[] estr = rsa.RSAEncrypt(str_encrode.getBytes()); // 密文 String ciphertext = Base64.encodeToString(estr, Base64.DEFAULT); return ciphertext; } catch (Exception e) { e.printStackTrace(); } return null; } 有疑问的留言
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

私房菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值