Python Java interworking rsa encryption and decryption

Keywords: Python Java OpenSSL encoding

Record a project using RSA encryption and decryption

The project is under development in Java and Python, RSA encryption and decryption interworking Code:

Python code

# -*- coding: utf-8 -*-
"""
RSA Encryption and decryption
"""
import base64
from M2Crypto import BIO, RSA

with open("public_key.pem", 'r') as f:
    pubkey = f.read()
with open("private_key.pem", 'r') as f:
    prikey = f.read()

# encryption
text = "ABCDEF".encode('utf-8')  # Plaintext
pub_bio = BIO.MemoryBuffer(pubkey.encode('utf-8'))  # Public key string
pub_rsa = RSA.load_pub_key_bio(pub_bio)  # Load public key
secret = pub_rsa.public_encrypt(text, RSA.pkcs1_padding)  # Public key encryption
sign = base64.b64encode(secret)  # Ciphertext base64 encoding
print(sign)

# decrypt
b64_sign = "uhBqhevT0E5+WT++HX+pGzSy7YGskBQODuvoV+hf0k8cSyXG/GuAT4LKYaCiT9qiEGlbWxCIH51Qt1s0y2X56TbNja93AbzXiFWzsC2H6vwo3ZFcoj+YqUBsax+Gad0I6NME9lalpKsPtWqi4W/b3VbG5Mx+WBJ+L17GR7ZvWMo=" # base64 ciphertext
cipher = base64.b64decode(b64_sign)  # base64 decoding
pri_bio = BIO.MemoryBuffer(prikey.encode('utf-8'))  # Load private key
pri_rsa = RSA.load_key_bio(pri_bio)
plain = pri_rsa.private_decrypt(cipher, RSA.pkcs1_padding)  # decrypt
print(plain.decode('utf-8'))

Java code

import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

import javax.crypto.Cipher;

public class rsa_demo {
    
    public String encryptoMode ="RSA/ECB/PKCS1Padding";
    //public String encryptoMode ="RSA/ECB/NoPadding";

    private String priKey="Private key string";
    
    private String pubKey="Public key string";
    
    public String sign_str = "123456" ;
     /***
      * Generation of secret key by openssl
      */
     
     /**
      * Get public key
      * @return
     * @throws NoSuchAlgorithmException 
     * @throws InvalidKeySpecException 
      */
     private PublicKey getPublicKey(String pubKeyString) throws NoSuchAlgorithmException, InvalidKeySpecException {
         byte[] pubKeyByte = Base64.getDecoder().decode(pubKey);
         X509EncodedKeySpec spec = new X509EncodedKeySpec(pubKeyByte);
         KeyFactory keyFactory = KeyFactory.getInstance("RSA");    
         PublicKey pubkey = keyFactory.generatePublic(spec); 
         return pubkey;
     }
     /**
      * Get private key
      * @return
      */
     private PrivateKey getPrivateKey(String priKeyString) throws NoSuchAlgorithmException, InvalidKeySpecException {
         byte[] priKeyByte = Base64.getDecoder().decode(priKey);
         PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(priKeyByte);
         KeyFactory keyFactory = KeyFactory.getInstance("RSA");    
         PrivateKey priKey = keyFactory.generatePrivate(spec);    
         return priKey;
     }
     
     /**
      * Public key encryption (private key encryption)
      */
     public String encrypto(String text,Key key) {
         try{
                Cipher cipher = Cipher.getInstance(encryptoMode);
                cipher.init(Cipher.ENCRYPT_MODE, key);
                byte tempBytes[] = cipher.doFinal(text.getBytes());
                String secretText=Base64.getEncoder().encodeToString(tempBytes);
                return secretText;
            }catch(Exception e){
                throw new RuntimeException("Encrypted string[" + text + "]Exception encountered at", e);
            }
     }
     /**
      * Private key decryption (public key decryption)
      * @param secretText
      */
     public String decrypto(String secretText,Key key) {
         try{
                //Generate public key
                Cipher cipher = Cipher.getInstance(encryptoMode);
                cipher.init(Cipher.DECRYPT_MODE, key);
                // Ciphertext decoding
                byte[] secretText_decode = Base64.getDecoder().decode(secretText.getBytes());
                byte tempBytes[] = cipher.doFinal(secretText_decode);
                String text=new String( tempBytes);
                return text;
            }catch(Exception e){
                throw new RuntimeException("Decrypt string[" + secretText + "]Exception encountered at", e);
            }
     }
    /**
     * Because the result of public key encryption is different every time, the result of all python java encryption is different every time, and there is no comparability. We only think about decryption 
     * @param args
     */
    public static void main(String[] args) throws Exception {
        
        rsa_demo rsa = new rsa_demo();
        System.err.println("Plaintext:"+rsa.sign_str);
        PublicKey pubkey = rsa.getPublicKey(rsa.pubKey);
        PrivateKey prikey = rsa.getPrivateKey(rsa.priKey);
        String secretText = rsa.encrypto(rsa.sign_str,pubkey);//Public key encryption, private key decryption
    
        secretText="Lm9PN4oM1dl17d2XFYRIs+hDV6RkGPVYBjgYAglaj020v5RnYzClHUN6lOVBzpeYKyH1MY5JzyOfxuYZHKCupVqhcvY4+zx+jowBH2nbVp1+/OrzuiPkNivfvmEad6ImAZp5/3Y/dVafABm5xZE78j7Ytlv0ak4seXMGTisU39o=";
        System.out.println("ciphertext:"+secretText);
        String text =  rsa.decrypto(secretText,prikey);
        
        System.out.println("Plaintext:"+text);
        
    }
    
    
}

note

1 public key and private key: use openssl to generate a public key and private key pem file in PKCs 񖓿 1 format. python uses the key directly; Java needs to convert to PKCs ා 8 format public key and private key, and the key string does not need BEGIN/END.
2 python can save and use the string of public key and private key directly, avoiding reading pem file every time.
3. There will be environmental problems in the installation of m2crypto library. The installation of centOS direct pip succeeded, and the installation of Ubuntu failed.

Posted by consultant1027 on Mon, 16 Dec 2019 08:55:20 -0800