/** Unmarshals a binary field value. */ protected static Object unmarshalBase64SortValue(Object value) { if (null == value) { return null; } final String val = (String) value; final byte[] bytes = Base64.base64ToByteArray(val); return new BytesRef(bytes); }
public static PublicKey deserializeX509PublicKey(String pubKey) { try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.base64ToByteArray(pubKey)); return keyFactory.generatePublic(publicKeySpec); } catch (Exception e) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e); } }
public static String decodeAES(String base64CipherTxt, String pwd, final int keySizeBits) { final Charset ASCII = Charset.forName("ASCII"); final int INDEX_KEY = 0; final int INDEX_IV = 1; final int ITERATIONS = 1; final int SALT_OFFSET = 8; final int SALT_SIZE = 8; final int CIPHERTEXT_OFFSET = SALT_OFFSET + SALT_SIZE; try { byte[] headerSaltAndCipherText = Base64.base64ToByteArray(base64CipherTxt); // --- extract salt & encrypted --- // header is "Salted__", ASCII encoded, if salt is being used (the default) byte[] salt = Arrays.copyOfRange(headerSaltAndCipherText, SALT_OFFSET, SALT_OFFSET + SALT_SIZE); byte[] encrypted = Arrays.copyOfRange( headerSaltAndCipherText, CIPHERTEXT_OFFSET, headerSaltAndCipherText.length); // --- specify cipher and digest for evpBytesTokey method --- Cipher aesCBC = Cipher.getInstance("AES/CBC/PKCS5Padding"); MessageDigest md5 = MessageDigest.getInstance("MD5"); // --- create key and IV --- // the IV is useless, OpenSSL might as well have use zero's final byte[][] keyAndIV = evpBytesTokey( keySizeBits / Byte.SIZE, aesCBC.getBlockSize(), md5, salt, pwd.getBytes(ASCII), ITERATIONS); SecretKeySpec key = new SecretKeySpec(keyAndIV[INDEX_KEY], "AES"); IvParameterSpec iv = new IvParameterSpec(keyAndIV[INDEX_IV]); // --- initialize cipher instance and decrypt --- aesCBC.init(Cipher.DECRYPT_MODE, key, iv); byte[] decrypted = aesCBC.doFinal(encrypted); return new String(decrypted, ASCII); } catch (BadPaddingException e) { // AKA "something went wrong" throw new IllegalStateException( "Bad password, algorithm, mode or padding;" + " no salt, wrong number of iterations or corrupted ciphertext.", e); } catch (IllegalBlockSizeException e) { throw new IllegalStateException("Bad algorithm, mode or corrupted (resized) ciphertext.", e); } catch (GeneralSecurityException e) { throw new IllegalStateException(e); } }
/** Try with all signatures and return the name of the signature that matched */ public String verify(String sig, ByteBuffer data) { exception = null; for (Map.Entry<String, PublicKey> entry : keys.entrySet()) { boolean verified; try { verified = CryptoKeys.verify(entry.getValue(), Base64.base64ToByteArray(sig), data); log.info("verified {} ", verified); if (verified) return entry.getKey(); } catch (Exception e) { exception = e; log.info("NOT verified "); } } return null; }