public byte[] new_decrypt_cn(E_CODE paramE_CODE, byte[] paramArrayOfByte)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
          InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    byte[] localObject = null;

    if (paramE_CODE == E_CODE.RSA) {
      if (rsa_key.length() > 2) {
        Cipher localCipher;
        byte[] arrayOfByte = new byte[0];
        //		    PublicKey localPublicKey = KeyFactory.getInstance("RSA").generatePublic(new
        // X509EncodedKeySpec(Base64.decodeBase64(rsa_key)));
        PublicKey localPublicKey =
            KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(Base64.decode(rsa_key, Base64.DEFAULT)));
        System.out.println("key  length-" + (Base64.decode(rsa_key, Base64.DEFAULT)).length);
        System.out.println("data length-" + paramArrayOfByte.length);
        localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        localCipher.init(Cipher.DECRYPT_MODE, localPublicKey);
        //		    localCipher.init(Cipher.ENCRYPT_MODE, localPublicKey);

        arrayOfByte = localCipher.doFinal(paramArrayOfByte);
        //		    int oldLength;
        //		    for (int i = 0; i < paramArrayOfByte.length; i += 8) {
        //		        byte[] temp = localCipher.doFinal(paramArrayOfByte, i, i + 8);
        //		        oldLength = arrayOfByte.length;
        //		        arrayOfByte  = Arrays.copyOf(arrayOfByte, temp.length+arrayOfByte.length);
        //		        System.arraycopy(temp, 0, arrayOfByte, oldLength, temp.length);
        //		    }

        //		    arrayOfByte = paramArrayOfByte;

        return arrayOfByte;
      }
    } else if (paramE_CODE == E_CODE.RSA_EP) {
      if (rsa_ep_key.length() >= 2) {
        //        PrivateKey localPrivateKey = KeyFactory.getInstance("RSA").generatePrivate(new
        // PKCS8EncodedKeySpec(Base64.decodeBase64(rsa_ep_key)));
        PrivateKey localPrivateKey =
            KeyFactory.getInstance("RSA")
                .generatePrivate(
                    new PKCS8EncodedKeySpec(Base64.decode(rsa_ep_key, Base64.DEFAULT)));
        Cipher localCipher2 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        localCipher2.init(2, localPrivateKey);
        localObject = localCipher2.doFinal(paramArrayOfByte);
      }
    } else if (paramE_CODE == E_CODE.AES) {
      //      SecretKeySpec localSecretKeySpec = new
      // SecretKeySpec(Base64.decodeBase64(aes_key.getBytes()), "AES");
      //      byte[] arrayOfByte1 = Base64.decodeBase64(paramArrayOfByte);
      SecretKeySpec localSecretKeySpec =
          new SecretKeySpec(Base64.decode(aes_key.getBytes(), Base64.DEFAULT), "AES");
      byte[] arrayOfByte1 = Base64.decode(paramArrayOfByte, Base64.DEFAULT);
      Cipher localCipher1 = Cipher.getInstance("AES/ECB/PKCS5Padding");
      localCipher1.init(Cipher.DECRYPT_MODE, localSecretKeySpec);
      byte[] arrayOfByte2 = localCipher1.doFinal(arrayOfByte1);
      localObject = arrayOfByte2;
    }

    return localObject;
  }
  public static void main(String[] args) throws Exception {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    // get user inputted key
    byte[] userkey = null;
    do {
      System.out.println("Please enter a 8 character string to generate a Secret Key");
      userkey = (in.readLine()).getBytes();
    } while (userkey.length != 8);

    // create Key Generator instance and generate a secret key
    KeyGenerator kgen = KeyGenerator.getInstance("DES");
    SecretKey skey = kgen.generateKey();

    byte[] key = userkey;
    // Create a Secret Key based on characters entered by the user
    SecretKeySpec skeyspec = new SecretKeySpec(key, "DES");

    // Create a cipher to encrypt with
    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, skeyspec);

    // Get message
    System.out.println("Please enter a string to encrypt");
    byte[] userstring = null;
    userstring = (in.readLine()).getBytes();

    // Encrypt message with cipher
    byte[] encrypted = cipher.doFinal(userstring);
    String enc_string = new String(encrypted);
    System.out.println("The String is encrypted as " + enc_string);

    byte[] userdecrypt = null;
    byte[] decrypted = null;

    // Get user decrypt key
    do {
      System.out.println("Please enter the 8 character key to decrypt the message");
      userdecrypt = (in.readLine()).getBytes();
    } while (userdecrypt.length != 8);

    // Reinitialize Secret Key and Cipher
    key = userdecrypt;
    SecretKeySpec decryptkey = new SecretKeySpec(key, "DES");
    cipher.init(Cipher.DECRYPT_MODE, decryptkey);

    // Decrypt message
    decrypted = cipher.doFinal(encrypted);

    if ((new String(decrypted)).equals(new String(userstring)))
      System.out.println("\nMessage decrypted as: " + (new String(decrypted)));
    else System.out.println("\nMessage was not decrypted");
  }
Beispiel #3
0
  /**
   * @param s
   * @return
   * @throws GeneralSecurityException
   * @throws UnsupportedEncodingException
   */
  public static String decrypt(final String s)
      throws GeneralSecurityException, UnsupportedEncodingException {
    String decrypted = null;

    try {
      if (s != null) {
        final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        final SecretKey secretKey =
            secretKeyFactory.generateSecret(new PBEKeySpec(secret.toCharArray()));
        final Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new PBEParameterSpec(SALT, 20));
        final byte[] stringBytes = s.getBytes("UTF-8");
        final byte[] decodedBytes = Base64.decode(stringBytes, Base64.DEFAULT);
        final byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        decrypted = new String(decryptedBytes, "UTF-8");
      }
    } catch (GeneralSecurityException x) {
      throw x;
    } catch (UnsupportedEncodingException x) {
      throw x;
    } catch (Exception x) {
      DBG.m(x);
    }

    return decrypted;
  }
Beispiel #4
0
  /*
   * Encrypt private key using Password-based encryption (PBE)
   * as defined in PKCS#5.
   *
   * NOTE: Currently pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is
   *       used to derive the key and IV.
   *
   * @return encrypted private key encoded as EncryptedPrivateKeyInfo
   */
  private byte[] encryptPrivateKey(byte[] data, char[] password)
      throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException {
    byte[] key = null;

    try {
      // create AlgorithmParameters
      AlgorithmParameters algParams = getAlgorithmParameters("PBEWithSHA1AndDESede");

      // Use JCE
      SecretKey skey = getPBEKey(password);
      Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
      cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
      byte[] encryptedKey = cipher.doFinal(data);

      // wrap encrypted private key in EncryptedPrivateKeyInfo
      // as defined in PKCS#8
      AlgorithmId algid = new AlgorithmId(pbeWithSHAAnd3KeyTripleDESCBC_OID, algParams);
      EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(algid, encryptedKey);
      key = encrInfo.getEncoded();
    } catch (Exception e) {
      UnrecoverableKeyException uke =
          new UnrecoverableKeyException("Encrypt Private Key failed: " + e.getMessage());
      uke.initCause(e);
      throw uke;
    }

    return key;
  }
 /**
  * Extract the enclosed PKCS8EncodedKeySpec object from the encrypted data and return it.
  *
  * @return the PKCS8EncodedKeySpec object.
  * @exception InvalidKeySpecException if the given cipher is inappropriate for the encrypted data
  *     or the encrypted data is corrupted and cannot be decrypted.
  */
 public PKCS8EncodedKeySpec getKeySpec(Cipher c) throws InvalidKeySpecException {
   try {
     return new PKCS8EncodedKeySpec(c.doFinal(this.getEncryptedData()));
   } catch (Exception e) {
     throw new InvalidKeySpecException("can't get keySpec: " + e.toString());
   }
 }
  public void run() {
    try {
      ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
      ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());

      BigInteger bg = dhSpec.getG();
      BigInteger bp = dhSpec.getP();
      oos.writeObject(bg);
      oos.writeObject(bp);

      KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
      kpg.initialize(1024);
      KeyPair kpa = (KeyPair) ois.readObject();
      KeyAgreement dh = KeyAgreement.getInstance("DH");
      KeyPair kp = kpg.generateKeyPair();

      oos.writeObject(kp);

      dh.init(kp.getPrivate());
      Key pk = dh.doPhase(kpa.getPublic(), true);

      MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
      byte[] rawbits = sha256.digest(dh.generateSecret());

      Cipher c = Cipher.getInstance(CIPHER_MODE);
      SecretKey key = new SecretKeySpec(rawbits, 0, 16, "AES");
      byte ivbits[] = (byte[]) ois.readObject();
      IvParameterSpec iv = new IvParameterSpec(ivbits);
      c.init(Cipher.DECRYPT_MODE, key, iv);

      Mac m = Mac.getInstance("HmacSHA1");
      SecretKey mackey = new SecretKeySpec(rawbits, 16, 16, "HmacSHA1");
      m.init(mackey);

      byte ciphertext[], cleartext[], mac[];
      try {
        while (true) {
          ciphertext = (byte[]) ois.readObject();
          mac = (byte[]) ois.readObject();
          if (Arrays.equals(mac, m.doFinal(ciphertext))) {
            cleartext = c.update(ciphertext);
            System.out.println(ct + " : " + new String(cleartext, "UTF-8"));
          } else {
            // System.exit(1);
            System.out.println(ct + "error");
          }
        }
      } catch (EOFException e) {
        cleartext = c.doFinal();
        System.out.println(ct + " : " + new String(cleartext, "UTF-8"));
        System.out.println("[" + ct + "]");
      } finally {
        if (ois != null) ois.close();
        if (oos != null) oos.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #7
0
 public String decrypt(String str) {
   try {
     return new String(cipherDecrypt.doFinal(StringUtils.hex2byte(str)), "UTF8");
   } catch (UnsupportedEncodingException e) {
   } catch (BadPaddingException e) {
   } catch (IllegalBlockSizeException e) {
   }
   return null;
 }
 public byte[] decrypt(final byte[] toDecrypt) {
   try {
     final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
     cipher.init(Cipher.DECRYPT_MODE, skey, sRand);
     return cipher.doFinal(toDecrypt);
   } catch (final Exception e) {
     throw new RuntimeException(e);
   }
 }
Beispiel #9
0
 public String encrypt(String str) {
   try {
     return StringUtils.byte2hex(cipherEncrypt.doFinal(str.getBytes("UTF8")));
   } catch (UnsupportedEncodingException e) {
   } catch (BadPaddingException e) {
   } catch (IllegalBlockSizeException e) {
   }
   return null;
 }
Beispiel #10
0
 private String decrypt(String s) {
   try {
     byte[] encrypted = b64Decoder.decodeBuffer(s);
     byte[] decrypted = deCipher.doFinal(encrypted);
     return new String(decrypted);
   } catch (Exception ex) {
     return "error";
   }
 }
  public byte[] new_encrypt_cn(E_CODE paramE_CODE, String val) {
    byte[] localObject = null;
    try {
      if (paramE_CODE == E_CODE.RSA) {
        /*if (rsa_key.length() > 2)
        {
            Cipher localCipher;
            byte[] arrayOfByte = null;
            PublicKey localPublicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.decodeBase64(rsa_key)));
            localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            localCipher.init(Cipher.ENCRYPT_MODE, localPublicKey);
            arrayOfByte = localCipher.doFinal(val.getBytes());
            return arrayOfByte;
        }*/
        return null;
      } else if (paramE_CODE == E_CODE.RSA_EP) {
        if (rsa_key.length() >= 2) {
          Cipher localCipher;
          PublicKey localPublicKey;

          //  		byte[] b = Base64.decodeBase64(rsa_key);
          byte[] b = Base64.decode(rsa_key, Base64.DEFAULT);
          X509EncodedKeySpec sp = new X509EncodedKeySpec(b);
          localPublicKey = KeyFactory.getInstance("RSA").generatePublic(sp);
          localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
          localCipher.init(Cipher.ENCRYPT_MODE, localPublicKey);
          localObject = localCipher.doFinal(val.getBytes("utf-8"));
        }
      } else if (paramE_CODE == E_CODE.AES) {
        //    SecretKeySpec localSecretKeySpec = new
        // SecretKeySpec(Base64.decodeBase64(aes_key.getBytes()), "AES");
        SecretKeySpec localSecretKeySpec =
            new SecretKeySpec(Base64.decode(aes_key.getBytes(), Base64.DEFAULT), "AES");
        Cipher localCipher1 = Cipher.getInstance("AES/ECB/PKCS5Padding");
        localCipher1.init(Cipher.ENCRYPT_MODE, localSecretKeySpec);
        localObject = localCipher1.doFinal(val.getBytes());
        //       = arrayOfByte2;
      }
    } catch (Exception localException) {
      System.out.println("new _e_cn-" + localException);
      return null;
    }
    return localObject;
  }
Beispiel #12
0
 /**
  * 加密字节数组
  *
  * @param arrB 需加密的字节数组
  * @return 加密后的字节数组
  * @throws Exception
  */
 public byte[] encrypt(byte[] arrB) {
   try {
     return encryptCipher.doFinal(arrB);
   } catch (IllegalBlockSizeException e) {
     e.printStackTrace();
   } catch (BadPaddingException e) {
     e.printStackTrace();
   }
   return arrB;
 }
 public static byte[] decode(byte[] paramArrayOfByte1, byte[] paramArrayOfByte2) {
   SecretKeySpec localSecretKeySpec = new SecretKeySpec(paramArrayOfByte2, "AES");
   try {
     Cipher localCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
     localCipher.init(Cipher.DECRYPT_MODE, localSecretKeySpec);
     byte[] arrayOfByte = localCipher.doFinal(paramArrayOfByte1);
     return arrayOfByte;
   } catch (Exception localException) {
     localException.printStackTrace();
   }
   return null;
 }
 public static byte[] encode(String paramString, byte[] paramArrayOfByte) {
   SecretKeySpec localSecretKeySpec = new SecretKeySpec(paramArrayOfByte, "AES");
   try {
     byte[] arrayOfByte1 = paramString.getBytes();
     Cipher localCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
     localCipher.init(Cipher.ENCRYPT_MODE, localSecretKeySpec);
     byte[] arrayOfByte2 = localCipher.doFinal(arrayOfByte1);
     return arrayOfByte2;
   } catch (Exception localException) {
   }
   return null;
 }
Beispiel #15
0
  /**
   * Uses a cipher to transform the bytes in an input stream and sends the transformed bytes to an
   * output stream.
   *
   * @param in the input stream
   * @param out the output stream
   * @param cipher the cipher that transforms the bytes
   */
  public static void crypt(InputStream in, OutputStream out, Cipher cipher)
      throws IOException, GeneralSecurityException {
    int blockSize = cipher.getBlockSize();
    int outputSize = cipher.getOutputSize(blockSize);
    byte[] inBytes = new byte[blockSize];
    byte[] outBytes = new byte[outputSize];

    int inLength = 0;
    ;
    boolean more = true;
    while (more) {
      inLength = in.read(inBytes);
      if (inLength == blockSize) {
        int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
        out.write(outBytes, 0, outLength);
      } else more = false;
    }
    if (inLength > 0) outBytes = cipher.doFinal(inBytes, 0, inLength);
    else outBytes = cipher.doFinal();
    out.write(outBytes);
  }
Beispiel #16
0
 /**
  * Reads the raw data from the input File, encrypts and saves its contents to the output File, and
  * then save the raw data of the SecretKey used to the SecretKey File.
  *
  * @param input the File to be read and encrypted
  * @param output the File the encrypted data will be saved to
  * @param keyFile the File the SecretKey data will be saved to
  * @throws InvalidKeyException if the given key is inappropriate for initializing this cipher, or
  *     if this cipher is being initialized for decryption and requires algorithm parameters that
  *     cannot be determined from the given key, or if the given key has a keysize that exceeds the
  *     maximum allowable keysize (as determined from the configured jurisdiction policy files).
  * @throws IOException if any of the files do not exist, are a directory rather than a regular
  *     file, or for some other reason cannot be opened for reading or if an I/O error occurs.
  * @throws IllegalBlockSizeException if the cipher is a block cipher, no padding has been
  *     requested (only in encryption mode), and the total input length of the data processed by
  *     this cipher is not a multiple of block size; or if this encryption algorithm is unable to
  *     process the input data provided.
  * @throws BadPaddingException if the cipher is in decryption mode, and (un)padding has been
  *     requested, but the decrypted data is not bounded by the appropriate padding bytes
  */
 public void encrypt(File input, File output, File keyFile)
     throws InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException {
   if (debug) {
     System.out.println("Initializing encryption...");
   }
   cipher.init(Cipher.ENCRYPT_MODE, key);
   FileInputStream fis = null;
   try {
     fis = new FileInputStream(input);
     data = new byte[(int) input.length()];
     if (debug) {
       System.out.println("Reading data...");
     }
     fis.read(data);
   } finally {
     if (fis != null) {
       fis.close();
     }
   }
   if (debug) {
     System.out.println("Encrypting data...");
   }
   data = cipher.doFinal(data);
   FileOutputStream fos = null;
   try {
     fos = new FileOutputStream(output);
     if (debug) {
       System.out.println("Saving data...");
     }
     fos.write(data);
   } finally {
     if (fos != null) {
       fos.close();
     }
   }
   if (debug) {
     System.out.println("Saving key...");
   }
   data = key.getEncoded();
   fos = null;
   try {
     fos = new FileOutputStream(keyFile);
     fos.write(data);
   } finally {
     if (fos != null) {
       fos.close();
     }
   }
   if (debug) {
     System.out.println("Encryption complete!");
   }
   data = null;
 }
Beispiel #17
0
  /**
   * Decrypts the given input data.
   *
   * @param in data to decrypt
   * @param k secret key
   * @param a encryption algorithm
   * @param ivl initialization vector length
   * @return decrypted data
   * @throws NoSuchAlgorithmException ex
   * @throws NoSuchPaddingException ex
   * @throws InvalidKeyException ex
   * @throws InvalidAlgorithmParameterException ex
   * @throws IllegalBlockSizeException ex
   * @throws BadPaddingException ex
   */
  private static byte[] decrypt(final byte[] in, final byte[] k, final byte[] a, final int ivl)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
          InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

    final SecretKeySpec keySpec = new SecretKeySpec(k, string(a));
    final Cipher cipher = Cipher.getInstance(string(ALGN.get(lc(a))));

    // extract iv from message beginning
    final byte[] iv = substring(in, 0, ivl);
    final IvParameterSpec ivspec = new IvParameterSpec(iv);
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivspec);
    return cipher.doFinal(substring(in, ivl, in.length));
  }
 public static String encodeWithBase64(String paramString) {
   SecretKeySpec localSecretKeySpec = new SecretKeySpec(BaseSecretKey, "AES");
   try {
     byte[] arrayOfByte = paramString.getBytes();
     Cipher localCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
     localCipher.init(Cipher.ENCRYPT_MODE, localSecretKeySpec);
     //      String str = Base64.encodeBase64String(localCipher.doFinal(arrayOfByte));
     String str = new String(Base64.encode(localCipher.doFinal(arrayOfByte), Base64.DEFAULT));
     return str;
   } catch (Exception localException) {
   }
   return null;
 }
Beispiel #19
0
  // <editor-fold desc="Class Constructor" defaultstate="collapsed">
  public AES256Encrypt(char[] plaintext, char[] key)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
          IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException {

    // We have to convert the real key into a hash that can fit into the AES algorithm.
    hash = new SHA256Hash(key);
    secretKey = new SecretKeySpec(hash.getHash().getEncoded(), encryptionAlgorithm);

    // Creating the actual cipher
    cipher = Cipher.getInstance(encryptionAlgorithm);
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    encryptedCipher = cipher.doFinal(new String(plaintext).getBytes());
  }
Beispiel #20
0
  // DES±àÂë
  public String desEncrypt(String s) {
    try {
      byte[] utf8 = s.getBytes("UTF8");

      byte[] enc = ecipher.doFinal(utf8);

      return new sun.misc.BASE64Encoder().encode(enc);
    } catch (javax.crypto.BadPaddingException e) {
    } catch (IllegalBlockSizeException e) {
    } catch (UnsupportedEncodingException e) {
    } catch (java.io.IOException e) {
    }
    return null;
  }
  public static byte[] decode64(byte[] paramArrayOfByte) {
    SecretKeySpec localSecretKeySpec = new SecretKeySpec(BaseSecretKey, "AES");
    try {
      //      byte[] arrayOfByte1 = Base64.decodeBase64(paramArrayOfByte);
      byte[] arrayOfByte1 = Base64.decode(paramArrayOfByte, Base64.DEFAULT);

      Cipher localCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      localCipher.init(Cipher.DECRYPT_MODE, localSecretKeySpec);
      byte[] arrayOfByte2 = localCipher.doFinal(arrayOfByte1);
      return arrayOfByte2;
    } catch (Exception localException) {
      localException.printStackTrace();
    }
    return null;
  }
Beispiel #22
0
  // DES½âÂë
  public String desDecrypt(String s) {
    try {
      byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(s);

      // ½âÂë
      byte[] utf8 = dcipher.doFinal(dec);

      return new String(utf8, "UTF8");
    } catch (javax.crypto.BadPaddingException e) {
    } catch (IllegalBlockSizeException e) {
    } catch (UnsupportedEncodingException e) {
    } catch (java.io.IOException e) {
    }
    return null;
  }
 public static byte[] encryptData(Key key, byte[] toEncrypt) {
   try {
     Cipher cipher = Cipher.getInstance(key.getAlgorithm());
     cipher.init(Cipher.ENCRYPT_MODE, key);
     return cipher.doFinal(toEncrypt);
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (NoSuchPaddingException e) {
     e.printStackTrace();
   } catch (InvalidKeyException e) {
     e.printStackTrace();
   } catch (BadPaddingException e) {
     e.printStackTrace();
   } catch (IllegalBlockSizeException e) {
     e.printStackTrace();
   }
   return new byte[0];
 }
Beispiel #24
0
 @SuppressWarnings("restriction")
 public String getencrypt(String p) throws Exception {
   String encrypted = "";
   try {
     KeyGenerator kgen = KeyGenerator.getInstance("AES");
     kgen.init(128, new SecureRandom(KEY.getBytes()));
     SecretKey skey = kgen.generateKey();
     byte[] raw = skey.getEncoded();
     SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
     Cipher cipher = Cipher.getInstance("AES");
     cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
     byte[] encrypt = cipher.doFinal(p.getBytes());
     encrypted = new BASE64Encoder().encodeBuffer(encrypt).trim();
     // System.out.println("encrypted="+encrypted);
   } // try
   catch (Exception e) {
     System.out.println(e);
   }
   return encrypted; // return 密文
 }
Beispiel #25
0
  /**
   * Encrypts the given input data.
   *
   * @param in input data to encrypt
   * @param k key
   * @param a encryption algorithm
   * @param ivl initialization vector length
   * @return encrypted input data
   * @throws InvalidKeyException ex
   * @throws InvalidAlgorithmParameterException ex
   * @throws NoSuchAlgorithmException ex
   * @throws NoSuchPaddingException ex
   * @throws IllegalBlockSizeException ex
   * @throws BadPaddingException ex
   */
  private static byte[] encrypt(final byte[] in, final byte[] k, final byte[] a, final int ivl)
      throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
          NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {

    final Cipher cipher = Cipher.getInstance(string(ALGN.get(lc(a))));
    final SecretKeySpec kspec = new SecretKeySpec(k, string(a));
    // generate random iv. random iv is necessary to make the encryption of a
    // string look different every time it is encrypted.
    final byte[] iv = new byte[ivl];
    // create new random iv if encrypting
    final SecureRandom rand = SecureRandom.getInstance("SHA1PRNG");
    rand.nextBytes(iv);
    final IvParameterSpec ivspec = new IvParameterSpec(iv);

    // encrypt/decrypt
    cipher.init(Cipher.ENCRYPT_MODE, kspec, ivspec);
    final byte[] t = cipher.doFinal(in);
    // initialization vector is appended to the message for later decryption
    return concat(iv, t);
  }
  public String get_K() {
    if (rsa_key.length() < 2) return null;
    Cipher localCipher;
    byte[] arrayOfByte = null;

    PublicKey localPublicKey;
    try {
      //		byte[] b = Base64.decode(rsa_key);
      byte[] b = Base64.decode(rsa_key, Base64.DEFAULT);
      X509EncodedKeySpec sp = new X509EncodedKeySpec(b);
      localPublicKey = KeyFactory.getInstance("RSA").generatePublic(sp);
      localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      localCipher.init(Cipher.ENCRYPT_MODE, localPublicKey);
      arrayOfByte = localCipher.doFinal(aes_key.getBytes("utf-8"));
    } catch (Exception e) {
      // e.printStackTrace();
      return null;
    }
    //	return new String(Base64.encode(arrayOfByte));
    return new String(Base64.encode(arrayOfByte, Base64.DEFAULT));
  }
Beispiel #27
0
  public String getdecrypt(String base64) throws Exception {
    String decrypted = "";
    try {
      @SuppressWarnings("restriction")
      byte[] b = new BASE64Decoder().decodeBuffer(base64);
      KeyGenerator kgen2 = KeyGenerator.getInstance("AES");
      kgen2.init(128, new SecureRandom(KEY.getBytes()));
      SecretKey skey2 = kgen2.generateKey();
      byte[] raw2 = skey2.getEncoded();
      SecretKeySpec skeySpec2 = new SecretKeySpec(raw2, "AES");
      Cipher cipher2 = Cipher.getInstance("AES");
      cipher2.init(Cipher.DECRYPT_MODE, skeySpec2);
      byte[] decrypt = cipher2.doFinal(b);
      decrypted = new String(decrypt);
      // System.out.println("decrypted="+decrypted);

    } catch (Exception e) {
      System.out.println(e);
    }
    return decrypted;
  }
Beispiel #28
0
  /**
   * Returns the key associated with the given alias, using the given password to recover it.
   *
   * @param alias the alias name
   * @param password the password for recovering the key. This password is used internally as the
   *     key is exported in a PKCS12 format.
   * @return the requested key, or null if the given alias does not exist or does not identify a
   *     <i>key entry</i>.
   * @exception NoSuchAlgorithmException if the algorithm for recovering the key cannot be found
   * @exception UnrecoverableKeyException if the key cannot be recovered (e.g., the given password
   *     is wrong).
   */
  public Key engineGetKey(String alias, char[] password)
      throws NoSuchAlgorithmException, UnrecoverableKeyException {
    permissionCheck();

    // An empty password is rejected by MacOS API, no private key data
    // is exported. If no password is passed (as is the case when
    // this implementation is used as browser keystore in various
    // deployment scenarios like Webstart, JFX and applets), create
    // a dummy password so MacOS API is happy.
    if (password == null || password.length == 0) {
      // Must not be a char array with only a 0, as this is an empty
      // string.
      if (random == null) {
        random = new SecureRandom();
      }
      password = Long.toString(random.nextLong()).toCharArray();
    }

    Object entry = entries.get(alias.toLowerCase());

    if (entry == null || !(entry instanceof KeyEntry)) {
      return null;
    }

    // This call gives us a PKCS12 bag, with the key inside it.
    byte[] exportedKeyInfo = _getEncodedKeyData(((KeyEntry) entry).keyRef, password);
    if (exportedKeyInfo == null) {
      return null;
    }

    PrivateKey returnValue = null;

    try {
      byte[] pkcs8KeyData = fetchPrivateKeyFromBag(exportedKeyInfo);
      byte[] encryptedKey;
      AlgorithmParameters algParams;
      ObjectIdentifier algOid;
      try {
        // get the encrypted private key
        EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(pkcs8KeyData);
        encryptedKey = encrInfo.getEncryptedData();

        // parse Algorithm parameters
        DerValue val = new DerValue(encrInfo.getAlgorithm().encode());
        DerInputStream in = val.toDerInputStream();
        algOid = in.getOID();
        algParams = parseAlgParameters(in);

      } catch (IOException ioe) {
        UnrecoverableKeyException uke =
            new UnrecoverableKeyException(
                "Private key not stored as " + "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);
        uke.initCause(ioe);
        throw uke;
      }

      // Use JCE to decrypt the data using the supplied password.
      SecretKey skey = getPBEKey(password);
      Cipher cipher = Cipher.getInstance(algOid.toString());
      cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
      byte[] decryptedPrivateKey = cipher.doFinal(encryptedKey);
      PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(decryptedPrivateKey);

      // Parse the key algorithm and then use a JCA key factory to create the private key.
      DerValue val = new DerValue(decryptedPrivateKey);
      DerInputStream in = val.toDerInputStream();

      // Ignore this -- version should be 0.
      int i = in.getInteger();

      // Get the Algorithm ID next
      DerValue[] value = in.getSequence(2);
      AlgorithmId algId = new AlgorithmId(value[0].getOID());
      String algName = algId.getName();

      // Get a key factory for this algorithm.  It's likely to be 'RSA'.
      KeyFactory kfac = KeyFactory.getInstance(algName);
      returnValue = kfac.generatePrivate(kspec);
    } catch (Exception e) {
      UnrecoverableKeyException uke =
          new UnrecoverableKeyException("Get Key failed: " + e.getMessage());
      uke.initCause(e);
      throw uke;
    }

    return returnValue;
  }
 public byte[] decrypt(byte[] encryptedMessage) throws Exception {
   return _cipher.doFinal(encryptedMessage);
 }
Beispiel #30
0
 /**
  * 解密字节数组
  *
  * @param arrB 需解密的字节数组
  * @return 解密后的字节数组
  * @throws Exception
  */
 public byte[] decrypt(byte[] arrB) throws Exception {
   return decryptCipher.doFinal(arrB);
 }