Android get signature public and public key private key plus decryption method (recommended) _android

Source: Internet
Author: User
Tags base64 getmessage string format asymmetric encryption

The

looks like this:

The public class Getpublickey {/** * Gets the signature key * @param mcontext * @return * * protected static String Getsi
    Gninfo (context Mcontext) {String signcode = ""; try {packageinfo packageinfo = Mcontext.getpackagemanager (). Getpackageinfo (Getappinfo.getpackagename (mCo
      ntext), packagemanager.get_signatures);
      Signature[] signs = packageinfo.signatures;
 
      Signature sign = signs[0];
      Signcode = Parsesignature (Sign.tobytearray ());
    Signcode = Signcode.tolowercase ();
    catch (Exception e) {log.e (Constants.tag, E.getmessage (), E);
  return signcode;
    } protected static string Parsesignature (byte[] signature) {String sign = "";
      try {certificatefactory certfactory = certificatefactory. getinstance ("X.509");
      X509Certificate cert = (x509certificate) certfactory. Generatecertificate (New Bytearrayinputstream (signature));
      String PubKey = Cert.getpublickey (). toString ();String ss = subString (PubKey);
      SS = Ss.replace (",", "");
      SS = Ss.tolowercase ();
      int aa = Ss.indexof ("modulus");
      int bb = ss.indexof ("publicexponent");
    Sign = ss.substring (aa + 8, BB);
    catch (Certificateexception e) {log.e (Constants.tag, E.getmessage (), E);
  return sign;
    public static string SubString (string sub) {Pattern pp = pattern.compile ("\\s*|\t|\r|\n");
    Matcher mm = Pp.matcher (sub);
  Return Mm.replaceall ("");
 
}} package Com.example.xscamera;
Import Java.io.ByteArrayOutputStream;
Import Java.security.Key;
Import Java.security.KeyFactory;
Import Java.security.KeyPair;
Import Java.security.KeyPairGenerator;
Import Java.security.PrivateKey;
Import Java.security.PublicKey;
Import Java.security.Signature;
Import Java.security.interfaces.RSAPrivateKey;
Import Java.security.interfaces.RSAPublicKey;
Import Java.security.spec.PKCS8EncodedKeySpec;
Import Java.security.spec.X509EncodedKeySpec; Import Java.util.HaShmap;

Import Java.util.Map;
 
Import Javax.crypto.Cipher; /** * <p> * RSA public/private key/Signature Toolkit * <p> * The key in string format is BASE64 encoding format without special instructions <br/> * Because of the extremely slow speed of asymmetric encryption, the general file does not use it to encrypt  is to use symmetric encryption,<br/> * Asymmetric encryption algorithm can be used to encrypt the symmetric key, so that the security of the key to ensure the security of the data * </p> * * * public class rsautils{/** *
   
  Cryptographic algorithm RSA */public static final String key_algorithm = "RSA";
 
  /** * Signature Algorithm * * public static final String signature_algorithm = "Md5withrsa";
   
  /** * Get public key key/private static final String Public_key = "Locatorpublickey";
   
  /** * Gets the private key's key/private static final String Private_key = "Locatorprivatekey";
   
  /** * RSA Maximum encrypted plaintext size * * private static final int max_encrypt_block = 117;
 
  /** * RSA Maximum decryption Text size * * private static final int max_decrypt_block = 128; /** * <p> * Generate key pair (public and private) * </p> * * @return * @throws Exception * * MAP&L T
   String, Object> Genkeypair () throws Exception { Keypairgenerator Keypairgen = keypairgenerator.getinstance (key_algorithm);
    Keypairgen.initialize (1024);
    KeyPair KeyPair = Keypairgen.generatekeypair ();
    Rsapublickey PublicKey = (rsapublickey) keypair.getpublic ();
    Rsaprivatekey Privatekey = (rsaprivatekey) keypair.getprivate ();
    map<string, object> keymap = new hashmap<string, object> (2);
    Keymap.put (Public_key, PublicKey);
    Keymap.put (Private_key, Privatekey);
  return keymap; /** * <p> * Generates digital signatures for information with private key * </p> * * @param data encrypted @param privatekey private key (BASE64 Code) * * @return * @throws Exception/public static String sign (byte[] data, String Privatekey) throws exc
    eption {byte[] keybytes = Base64utils.decode (Privatekey);
    Pkcs8encodedkeyspec Pkcs8keyspec = new Pkcs8encodedkeyspec (keybytes);
    Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);
    Privatekey Privatek = keyfactory.generateprivate (Pkcs8keyspec); SignatuRe signature = signature.getinstance (signature_algorithm);
    Signature.initsign (Privatek);
    Signature.update (data);
  Return Base64utils.encode (Signature.sign ()); /** * <p> * Verify Digital signature * </p> * @param data encrypted * @param publickey public key (BASE64 code) * @param sign Digital Signature * * @return * @throws Exception */public static Boolean verify (byte[) data, String
    PublicKey, String sign) throws Exception {byte[] keybytes = Base64utils.decode (PublicKey);
    X509encodedkeyspec Keyspec = new X509encodedkeyspec (keybytes);
    Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);
    PublicKey Publick = Keyfactory.generatepublic (Keyspec);
    Signature Signature = signature.getinstance (signature_algorithm);
    Signature.initverify (Publick);
    Signature.update (data);
  Return signature.verify (Base64utils.decode (sign)); /** * <P> * Private key decryption * </p> * * @param encrypteddata Encrypted data * @parAm Privatekey private key (BASE64 encoded) * @return * @throws Exception/public static byte[] Decryptbyprivatekey (byte[) enc
    Rypteddata, String Privatekey) throws Exception {byte[] keybytes = Base64utils.decode (Privatekey);
    Pkcs8encodedkeyspec Pkcs8keyspec = new Pkcs8encodedkeyspec (keybytes);
    Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);
    Key Privatek = keyfactory.generateprivate (Pkcs8keyspec);
    Cipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ());
    Cipher.init (Cipher.decrypt_mode, Privatek);
    int inputlen = Encrypteddata.length;
    Bytearrayoutputstream out = new Bytearrayoutputstream ();
    int offSet = 0;
    Byte[] Cache;
    int i = 0; Fragment decryption while (Inputlen-offset > 0) {if (Inputlen-offset > Max_decrypt_block) {cache = CI
      Pher.dofinal (EncryptedData, OffSet, Max_decrypt_block);
      else {cache = cipher.dofinal (EncryptedData, OffSet, Inputlen-offset); } out.write (cAche, 0, cache.length);
      i++;
    OffSet = i * max_decrypt_block;
    } byte[] Decrypteddata = Out.tobytearray ();
    Out.close ();
  return decrypteddata; /** * <p> * Public Key decryption * </p> * * @param encrypteddata Encrypted data * @param publickey Public key (BASE64 encoding * @return * @throws Exception/public static byte[] Decryptbypublickey (byte[] EncryptedData, String Publick
    EY) throws Exception {byte[] keybytes = Base64utils.decode (PublicKey);
    X509encodedkeyspec X509keyspec = new X509encodedkeyspec (keybytes);
    Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);
    Key Publick = Keyfactory.generatepublic (X509keyspec);
    Cipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ());
    Cipher.init (Cipher.decrypt_mode, Publick);
    int inputlen = Encrypteddata.length;
    Bytearrayoutputstream out = new Bytearrayoutputstream ();
    int offSet = 0;
    Byte[] Cache;
    int i = 0; Decrypting a data fragment while (inputlen-ofFSet > 0) {if (Inputlen-offset > Max_decrypt_block) {cache = Cipher.dofinal (EncryptedData, OffSet,
      Max_decrypt_block);
      else {cache = cipher.dofinal (EncryptedData, OffSet, Inputlen-offset);
      } out.write (cache, 0, cache.length);
      i++;
    OffSet = i * max_decrypt_block;
    } byte[] Decrypteddata = Out.tobytearray ();
    Out.close ();
  return decrypteddata; /** * <p> * Public key encryption * </p> * @param data source @param publickey public key (BASE64 code) * @ret URN * @throws Exception */public static byte[] Encryptbypublickey (byte[] data, String PublicKey) throws exc
    eption {byte[] keybytes = Base64utils.decode (PublicKey);
    X509encodedkeyspec X509keyspec = new X509encodedkeyspec (keybytes);
    Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);
    Key Publick = Keyfactory.generatepublic (X509keyspec); Encrypt the data Cipher Cipher = cipher.getinstance (Keyfactory.getalgorIthm ());
    Cipher.init (Cipher.encrypt_mode, Publick);
    int inputlen = Data.length;
    Bytearrayoutputstream out = new Bytearrayoutputstream ();
    int offSet = 0;
    Byte[] Cache;
    int i = 0; Data fragment encryption while (Inputlen-offset > 0) {if (Inputlen-offset > Max_encrypt_block) {cache = CI
      Pher.dofinal (data, OffSet, Max_encrypt_block);
      else {cache = cipher.dofinal (data, OffSet, Inputlen-offset);
      } out.write (cache, 0, cache.length);
      i++;
    OffSet = i * max_encrypt_block;
    } byte[] EncryptedData = Out.tobytearray ();
    Out.close ();
  return EncryptedData; /** * <p> * Private key encryption * </p> * @param data source * @param privatekey private key (BASE64 code) * @re Turn * @throws Exception */public static byte[] Encryptbyprivatekey (byte[] data, String Privatekey) throws
    Exception {byte[] keybytes = Base64utils.decode (Privatekey); Pkcs8encodedkeyspec Pkcs8keyspec = nEW Pkcs8encodedkeyspec (keybytes);
    Keyfactory keyfactory = keyfactory.getinstance (key_algorithm);
    Key Privatek = keyfactory.generateprivate (Pkcs8keyspec);
    Cipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ());
    Cipher.init (Cipher.encrypt_mode, Privatek);
    int inputlen = Data.length;
    Bytearrayoutputstream out = new Bytearrayoutputstream ();
    int offSet = 0;
    Byte[] Cache;
    int i = 0; Data fragment encryption while (Inputlen-offset > 0) {if (Inputlen-offset > Max_encrypt_block) {cache = CI
      Pher.dofinal (data, OffSet, Max_encrypt_block);
      else {cache = cipher.dofinal (data, OffSet, Inputlen-offset);
      } out.write (cache, 0, cache.length);
      i++;
    OffSet = i * max_encrypt_block;
    } byte[] EncryptedData = Out.tobytearray ();
    Out.close ();
  return EncryptedData;
  /** * <p> * Get private key * </p> * * @param keymap Key pair * @return * @throws Exception * * PubliC Static String Getprivatekey (map<string, object> keymap) throws Exception {key key = (key) Keymap.get (PR
    Ivate_key);
  Return Base64utils.encode (key.getencoded ());
  /** * <p> * obtain public key * </p> * * @param keymap Key pair * @return * @throws Exception * * public static String Getpublickey (map<string, object> keymap) throws Exception {key key = (key) keymap.
    Get (Public_key);
  Return Base64utils.encode (key.getencoded ()); }
 
}

The above Android get signed public key and public key to decrypt the method (recommended) is small to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.