/** * AES加密字符串 * * @param content 需要被加密的字符串 * @return 密文 */ public static String aesDecrypt(String content) { try { byte[] encrypted1 = new BASE64Decoder().decodeBuffer(content); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keyspec = new SecretKeySpec(PASSWORD_KEY.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(PASSWORD_KEY.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); String originalString = new String(cipher.doFinal(encrypted1)); int length = originalString.length(); int ch = originalString.charAt(length - 1); return originalString.substring(0, length - ch); } catch (Exception e) { e.printStackTrace(); } return null; }
/** * <pre> * Base64编码的字符解码为图片 * * </pre> * * @param imageString * @return */ public static BufferedImage decodeToImage(String imageString) { BufferedImage image = null; byte[] imageByte; try { BASE64Decoder decoder = new BASE64Decoder(); imageByte = decoder.decodeBuffer(imageString); ByteArrayInputStream bis = new ByteArrayInputStream(imageByte); image = ImageIO.read(bis); bis.close(); } catch (Exception e) { throw new RuntimeException(e); } return image; }
public static String desEncrypt(String data){ try { if(data==null||data.equals("")){ return ""; } data=data.trim(); byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keyspec = new SecretKeySpec(ZFMPWD.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original); return originalString.trim(); } catch (Exception e) { e.printStackTrace(); return null; } }
public InvokeFunctionResponse invokeFunction(InvokeFunctionRequest request) throws ClientException, ServerException { HttpResponse response = client.doAction(request, CONTENT_TYPE_APPLICATION_STREAM, "POST"); InvokeFunctionResponse invokeFunctionResponse = new InvokeFunctionResponse(); invokeFunctionResponse.setContent(response.getContent()); invokeFunctionResponse.setPayload(response.getContent()); invokeFunctionResponse.setHeader(response.getHeaders()); invokeFunctionResponse.setStatus(response.getStatus()); Map<String, String> headers = response.getHeaders(); if (headers != null && headers.containsKey(HeaderKeys.INVOCATION_LOG_RESULT)) { try { String logResult = new String(new BASE64Decoder().decodeBuffer(headers.get(HeaderKeys.INVOCATION_LOG_RESULT))); invokeFunctionResponse.setLogResult(logResult); } catch (IOException e) { throw new ClientException(e); } } return invokeFunctionResponse; }
/** * 根据公钥Cer文本串读取公钥 * * @param pubKeyText * @return */ public static PublicKey getPublicKeyByText(String pubKeyText) { try { CertificateFactory certificateFactory = CertificateFactory.getInstance(BaofooRsaConst.KEY_X509); BufferedReader br = new BufferedReader(new StringReader(pubKeyText)); String line = null; StringBuilder keyBuffer = new StringBuilder(); while ((line = br.readLine()) != null) { if (!line.startsWith("-")) { keyBuffer.append(line); } } Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(keyBuffer.toString()))); return certificate.getPublicKey(); } catch (Exception e) { // log.error("解析公钥内容失败:", e); } return null; }
private static void generateImage(String imgStr,String path,String newFileName,String ext){ if (imgStr != null) { int p = imgStr.indexOf(","); String head = imgStr.substring(0, p); String datas = imgStr.substring(p + 1); System.out.println("FULL-Path:" + path + "\\" + newFileName + "." + ext); BASE64Decoder decoder = new BASE64Decoder(); try { // 解密 byte[] b = decoder.decodeBuffer(datas); // 处理数据 for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } OutputStream out1 = new FileOutputStream(path + "\\" + newFileName + "." + ext); out1.write(b); out1.flush(); out1.close(); } catch (Exception e) { e.printStackTrace(); } } }
/** * 3-DES解密 * * @param String * src 要进行3-DES解密的String * @param String * spkey分配的SPKEY * @return String 3-DES加密后的String */ public static String get3DESDecrypt(String src, String spkey) { String requestValue = ""; try { // 得到3-DES的密钥匙 // URLDecoder.decodeTML控制码进行转义的过程 String URLValue = getURLDecoderdecode(src); // 进行3-DES加密后的内容进行BASE64编码 BASE64Decoder base64Decode = new BASE64Decoder(); byte[] base64DValue = base64Decode.decodeBuffer(URLValue); // 要进行3-DES加密的内容在进行/"UTF-16LE/"取字节 requestValue = deCrypt(base64DValue, spkey); } catch (Exception e) { e.printStackTrace(); } return requestValue; }
/** * 对字节数组字符串进行Base64解码并生成图片 * @param imgStr 转换为图片的字符串 * @param imgCreatePath 将64编码生成图片的路径 * @return */ public static boolean generateImage(String imgStr, String imgCreatePath){ if (imgStr == null) //图像数据为空 return false; BASE64Decoder decoder = new BASE64Decoder(); try { //Base64解码 byte[] b = decoder.decodeBuffer(imgStr); for(int i=0;i<b.length;++i) { if(b[i] < 0) {//调整异常数据 b[i] += 256; } } OutputStream out = new FileOutputStream(imgCreatePath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e){ return false; } }
public JCas getJCas() throws RuntimeException { if (base64JCas == null) { return null; } try { byte[] bytes = new BASE64Decoder() .decodeBuffer(new ByteArrayInputStream(base64JCas.getBytes("utf-8"))); JCas jCas = JCasFactory.createJCas(); XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas()); return jCas; } catch (Exception e) { throw new RuntimeException(e); } }
public void getFromTokenStr(String tokenStr) { byte[] b; String result; if (tokenStr != null) { BASE64Decoder decoder = new BASE64Decoder(); try { b = decoder.decodeBuffer(URLDecoder.decode(tokenStr,"utf-8")); result = new String(b, "utf-8"); String[] list = result.split("::"); this.userId = list[0]; this.username = list[1]; String lo = list[2]; this.startTime = Long.valueOf(lo); } catch (Exception e) { e.printStackTrace(); } } }
public static String decodeBase64(String s) { if (s == null) { return null; } byte[] b; String result = null; if (s != null) { BASE64Decoder decoder = new BASE64Decoder(); try { b = decoder.decodeBuffer(s); result = new String(b, "UTF-8"); } catch (Exception e) { return null; } } return result; }
/** * 对字节数组字符串进行Base64解码并生成图片 * @param base64 图像的Base64编码字符串 * @param fileSavePath 图像要保存的地址 * @return */ public static boolean convertBase64ToImage(String base64, String fileSavePath) { if(base64 == null) return false; BASE64Decoder decoder = new BASE64Decoder(); // Base64解码 try { byte[] buffer = decoder.decodeBuffer(base64); for(int i = 0; i < buffer.length; i ++) { if(buffer[i] < 0) { buffer[i] += 256; } } // 生成JPEG图片 OutputStream out = new FileOutputStream(fileSavePath); out.write(buffer); out.flush(); out.close(); return true; } catch (IOException e) { e.printStackTrace(); } return false; }
public static String desencriptar(String passPhrase, String str) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IOException, IllegalBlockSizeException, BadPaddingException { Cipher ecipher = null; Cipher dcipher = null; java.security.spec.KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), SALT_BYTES, ITERATION_COUNT); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); ecipher = Cipher.getInstance(key.getAlgorithm()); dcipher = Cipher.getInstance(key.getAlgorithm()); java.security.spec.AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT_BYTES, ITERATION_COUNT); ecipher.init(1, key, paramSpec); dcipher.init(2, key, paramSpec); byte dec[] = (new BASE64Decoder()).decodeBuffer(str); byte utf8[] = dcipher.doFinal(dec); return new String(utf8, "UTF8"); }
/** * 解密 * @param src byte[] * @param password String * @return String * @throws Exception */ public static String decrypt(String decodeStr, String password) throws Exception { byte[] str=new BASE64Decoder().decodeBuffer(decodeStr); // DES算法要求有一个可信任的随机数源 SecureRandom random = new SecureRandom(); // 创建一个DESKeySpec对象 DESKeySpec desKey = new DESKeySpec(password.getBytes()); // 创建一个密匙工厂 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); // 将DESKeySpec对象转换成SecretKey对象 SecretKey securekey = keyFactory.generateSecret(desKey); // Cipher对象实际完成解密操作 Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, securekey, random); // 真正开始解密操作 byte[] passByte=cipher.doFinal(str); return new String(passByte); }
public AESDecryptor() { try { /* Derive the key, given password and salt. */ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec; spec = new PBEKeySpec(Constants.FRAMEWORK_NAME.toCharArray(), SALT, ITERATIONS, KEY_SIZE); SecretKey tmp = factory.generateSecret(spec); secret = new SecretKeySpec(tmp.getEncoded(), "AES"); // CBC = Cipher Block chaining // PKCS5Padding Indicates that the keys are padded cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // For production use commons base64 encoder base64Decoder = new BASE64Decoder(); } catch (Exception e) { throw new RuntimeException("Unable to initialize AESDecryptor", e); } }
public static String decrypt(String AESkey, String AESIV, Boolean baseEncode, String AESMode, String cipherText) throws Exception { byte[] keyValue = AESkey.getBytes(); Key skeySpec = new SecretKeySpec(keyValue, "AES"); byte[] iv = AESIV.getBytes(); IvParameterSpec ivSpec = new IvParameterSpec(iv); String cmode = AESMode; Cipher cipher = Cipher.getInstance(cmode); if (cmode.contains("CBC")) { cipher.init(2, skeySpec, ivSpec); } else { cipher.init(2, skeySpec); } byte[] cipherbytes = cipherText.getBytes(); if (baseEncode) { cipherbytes = (new BASE64Decoder()).decodeBuffer(cipherText); } byte[] original = cipher.doFinal(cipherbytes); return new String(original); }
/** * Base64解密 * @param s * @return */ public static String getFromBase64(String s) { byte[] b; String result = null; if (s != null) { BASE64Decoder decoder = new BASE64Decoder(); try { b = decoder.decodeBuffer(s); result = new String(b, "utf-8"); } catch (Exception e) { e.printStackTrace(); return null; } } return result; }
private BufferedImage decodeToImage(String imageString) throws IOException { BufferedImage image = null; ByteArrayInputStream bis = null; byte[] imageByte; try { BASE64Decoder decoder = new BASE64Decoder(); imageByte = decoder.decodeBuffer(imageString); bis = new ByteArrayInputStream(imageByte); image = ImageIO.read(bis); } catch (IOException e) { throw new IOException("Failed to decode string to image", e); } finally { if (bis != null) { bis.close(); } } return image; }
public static String unionPayWapNotify(Map<String, String> p) { BASE64Decoder decoder = new BASE64Decoder(); String req = p.get("notifyBody"); String[] strArr = req.split("\\|"); String cerPath = CertUtil.getCertPath("UNIONPAYWAP_USER_Notify_CRT"); String publicKey = EncDecUtil.getPublicCertKey("000000", cerPath); String content = null; try { String mm = RSACoder.decryptByPublicKey(strArr[1], publicKey); byte[] de = decoder.decodeBuffer(strArr[2]); byte[] b = DesUtil2.decrypt(de, mm.getBytes()); content = new String(b, "utf-8"); LogUtil.printInfoLog("UnionPayWap", "unionPayWapNotify", content); } catch (Exception e) { StringWriter trace = new StringWriter(); e.printStackTrace(new PrintWriter(trace)); LogUtil.printErrorLog("UnionPayWap", "unionPayWapNotify", trace.toString()); } return content; }
/** * 取得验签名工具 * 加载信任根证书 * @param rootCertificatePath 根证书路径 * @throws GeneralSecurityException * @throws IOException */ public static PKCS7Tool getVerifier(String rootCertificatePath) throws GeneralSecurityException, IOException { init(); //加载根证书 FileInputStream fis = null; Certificate rootCertificate = null; try { fis = new FileInputStream(rootCertificatePath); CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509"); try { rootCertificate = certificatefactory.generateCertificate(fis); } catch(Exception exception) { InputStream is = new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(fis)); rootCertificate = certificatefactory.generateCertificate(is); } } finally { if (fis != null) fis.close(); } PKCS7Tool tool = new PKCS7Tool(VERIFIER); tool.rootCertificate = rootCertificate; return tool; }
@Override protected JComponent createViewPanel() { final String png = myCell.getBase64String(); final JBLabel label = new JBLabel(); if (!StringUtil.isEmptyOrSpaces(png)) { try { byte[] btDataFile = new BASE64Decoder().decodeBuffer(png); BufferedImage image = ImageIO.read(new ByteArrayInputStream(btDataFile)); label.setIcon(new ImageIcon(image)); } catch (IOException e) { LOG.error("Couldn't parse image. " + e.getMessage()); } } label.setBackground(IpnbEditorUtil.getBackground()); label.setOpaque(true); return label; }
public static byte[][] readCiphersFromDisk(String filePath) { try { File f = new File(filePath); FileInputStream bais = new FileInputStream(f); BufferedInputStream bis = new BufferedInputStream(bais); ObjectInputStream ois = new ObjectInputStream(bis); String[] encodedCiphers = (String[]) ois.readObject(); ois.close(); byte[][] ciphers = new byte[encodedCiphers.length][]; BASE64Decoder decoder = new BASE64Decoder(); for (int i = 0; i < ciphers.length; i++) ciphers[i] = decoder.decodeBuffer(encodedCiphers[i]); return ciphers; } catch (Exception e) { e.printStackTrace(); return null; } }
public byte[] composeBodySha256(List<AppSignedInfo> listAsi) throws Exception { byte[] ret = null; int idSha = NDX_SHA256; List<AppSignedInfoEx> listAsiEx = new ArrayList<AppSignedInfoEx>(); // List<X509Certificate> chain = new ArrayList<X509Certificate>(); BASE64Decoder b64dec = new BASE64Decoder(); for (AppSignedInfo appSignedInfo : listAsi) { // AppSignedInfo appSignedInfo = listAsi.get(0); byte[] x509 = b64dec.decodeBuffer(appSignedInfo.getCertId()); X509Certificate cert = loadCert(x509); byte[] certHash = calcSha256(cert.getEncoded()); AppSignedInfoEx asiEx = new AppSignedInfoEx(appSignedInfo, cert, certHash, idSha); listAsiEx.add(asiEx); } ret = serv2048.buildCms(listAsiEx, -1); return ret; }
@POST @Path("/validate") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response validate(ValidateRequest req) throws Exception { ValidateResponse resp = new ValidateResponse(); try { BASE64Decoder b64dec = new BASE64Decoder(); byte[] sign = b64dec.decodeBuffer(req.getEnvelope()); byte[] sha1 = b64dec.decodeBuffer(req.getSha1()); byte[] sha256 = b64dec.decodeBuffer(req.getSha256()); Date dtSign = javax.xml.bind.DatatypeConverter.parseDateTime( req.getTime()).getTime(); boolean verifyCRL = "true".equals(req.getCrl()); int errorCode = util.validateSign(sign, sha1, sha256, dtSign, verifyCRL, resp); resp.setErrorCode(errorCode); return Response.status(200).entity(resp).build(); } catch (Exception e) { resp.setError(e.toString()); return Response.status(500).entity(resp).build(); } }
@POST @Path("/validate") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response validate(ValidateRequest req) throws Exception { ValidateResponse resp = new ValidateResponse(); try { BASE64Decoder b64dec = new BASE64Decoder(); byte[] sign = b64dec.decodeBuffer(req.getEnvelope()); byte[] sha1 = b64dec.decodeBuffer(req.getSha1()); byte[] sha256 = b64dec.decodeBuffer(req.getSha256()); Date dtSign = javax.xml.bind.DatatypeConverter.parseDateTime( req.getTime()).getTime(); boolean verifyCRL = "true".equals(req.getCrl()); util.validateSign(sign, sha1, sha256, dtSign, verifyCRL, resp); return Response.status(200).entity(resp).build(); } catch (Exception e) { resp.setError(e.toString()); return Response.status(500).entity(resp).build(); } }
/** * 解码 */ public static byte[] decryptBase64(String str){ if(str == null || str.length() == 0){ return null; } byte[] result = null; BASE64Decoder decoder = new BASE64Decoder(); try { result = decoder.decodeBuffer(str); } catch (IOException e) { logger.error("出错:decode base64 error:: " + e.getMessage() ); } return result; }
public static void main(String[] args) throws IOException { BASE64Decoder de = new BASE64Decoder(); byte[] result = de.decodeBuffer(data); InputStream in = new ByteArrayInputStream(result); ZipInputStream zip = new ZipInputStream(in); ZipEntry entry = zip.getNextEntry(); BufferedReader reader = new BufferedReader(new InputStreamReader(zip)); while(reader.ready()) { System.out.println(reader.readLine()); } MongoClient mongoClient = new MongoClient(); DB db = mongoClient.getDB("mydb"); DBCollection coll = db.getCollection("goods"); BasicDBObject doc = new BasicDBObject("name", "MongoDB") .append("type", "database") .append("count", 1) .append("info", new BasicDBObject("x", 203).append("y", 102)); coll.insert(doc); System.out.println(coll.findOne()); }
public static String decodeString(String encryptedPassword) { BASE64Decoder decoder = new BASE64Decoder(); try { byte[] passwordBytes = decoder.decodeBuffer(encryptedPassword); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, key); passwordBytes = cipher.doFinal(passwordBytes); return new String (passwordBytes, "UTF8"); } catch (Exception ex) { return encryptedPassword; } }
/** * 将 BASE64 编码的字符串 s 进行解码 * * @param s * @param charSet * @return */ public final static String decodeFromBASE64(String s, String charSet) { String decodedStr; if (StringUtils.trimToEmpty(s).equals("")) return ""; BASE64Decoder decoder = new BASE64Decoder(); try { byte[] b = decoder.decodeBuffer(s); if (StringUtils.trimToEmpty(charSet).equals("")) decodedStr = new String(b); else decodedStr = new String(b, charSet); return decodedStr; } catch (Exception e) { LogUtil.getAppLog().error("decodeFromBASE64 Error for the string: " + s + "with CharSet " + charSet, e); return ""; } }
/** * Description 根据键值进行解密 * * @param data * @param key * 加密键byte数组 * @return * @throws IOException * @throws Exception */ public static String decrypt(String data, String key) { if (data == null) return null; BASE64Decoder decoder = new BASE64Decoder(); try { byte[] buf = decoder.decodeBuffer(data); byte[] bt = decrypt(buf, key.getBytes()); return new String(bt); } catch(Exception e) { LogUtil.getCoreLog().error("decoder error:",e); } return data; }
private static String decrypt(String data, String key) throws Exception { try { if (key == null || key.length() != 16) { throw new RuntimeException("key error"); } String iv = "1234567812345678"; byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); byte[] original = cipher.doFinal(encrypted1); return new String(original).trim(); } catch (Exception e) { e.printStackTrace(); return null; } }
/** * AES解密 */ public static String aesDecrypt(String sSrc, String sKey, String sIv) throws Exception { // 判断Key是否正确 if (sKey == null) { throw new BusinessException(CommonStateEnum.BADREQ_PARA); } // 判断Key是否为16位 if (sKey.length() != 16) { throw new BusinessException(CommonStateEnum.BADREQ_PARA); } byte[] raw = sKey.getBytes("ASCII"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(sIv.getBytes()); System.out.println(); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密 byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original); return originalString; }
/** * Set header(s) on the given connection. * @param conn The connection to apply the header(s) to * @param p A source of header values for this connection, not used because * HeaderParser converts the fields to lower case, use raw instead * @param raw The raw header field. * @return true if all goes well, false if no headers were set. */ @Override public synchronized boolean setHeaders(HttpURLConnection conn, HeaderParser p, String raw) { try { String response; byte[] incoming = null; String[] parts = raw.split("\\s+"); if (parts.length > 1) { incoming = new BASE64Decoder().decodeBuffer(parts[1]); } response = hci.scheme + " " + new B64Encoder().encode( incoming==null?firstToken():nextToken(incoming)); conn.setAuthenticationProperty(getHeaderName(), response); return true; } catch (IOException e) { return false; } }
private BufferedImage decodeToImage(String imageString) throws IOException{ BufferedImage image = null; ByteArrayInputStream bis = null; byte[] imageByte; try { BASE64Decoder decoder = new BASE64Decoder(); imageByte = decoder.decodeBuffer(imageString); bis = new ByteArrayInputStream(imageByte); image = ImageIO.read(bis); } finally { if(bis != null) { try { bis.close(); } catch (IOException e) { log.error("Error occurred while closing the input stream", e); } } } return image; }
/** * 解密算法 * * @param cryptograph 密文 * @return * @throws Exception */ private static String decrypt(String cryptograph) throws Exception { Key privateKey; ObjectInputStream ois = null; try { /** 将文件中的私钥对象读出 */ ois = new ObjectInputStream(new FileInputStream( PRIVATE_KEY_FILE)); privateKey = (Key) ois.readObject(); } catch (Exception e) { throw e; } finally { ois.close(); } /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */ Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, privateKey); BASE64Decoder decoder = new BASE64Decoder(); byte[] b1 = decoder.decodeBuffer(cryptograph); /** 执行解密操作 */ byte[] b = cipher.doFinal(b1); return new String(b); }
public static PrivateKey readPrivateKey(File keyFile) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { // read key bytes FileInputStream in = new FileInputStream(keyFile); byte[] keyBytes = new byte[in.available()]; in.read(keyBytes); in.close(); String privateKey = new String(keyBytes, "UTF-8"); privateKey = privateKey.replaceAll("(-+BEGIN RSA PRIVATE KEY-+\\r?\\n|-+END RSA PRIVATE KEY-+\\r?\\n?)", ""); // don't use this for real projects! BASE64Decoder decoder = new BASE64Decoder(); keyBytes = decoder.decodeBuffer(privateKey); // generate private key PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(spec); }
public static String decrypt(String secret, String encrypted) { byte[] raw = secret.getBytes(Charsets.US_ASCII); if (raw.length != 16) { throw ExceptionUtils.asUnchecked(new IllegalArgumentException("Invalid key size.")); } SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16])); byte[] original = cipher.doFinal(new BASE64Decoder().decodeBuffer(encrypted)); return new String(original, Charsets.US_ASCII); } catch (Exception e) { throw ExceptionUtils.asUnchecked(e); } }