/** * Creates the Cipher Instance. */ private static Cipher createTheCipherInstance(int opMode, String transformation, Key key) { try { Cipher cipher = Cipher.getInstance(transformation); cipher.init(opMode, key); return cipher; } catch (InvalidKeyException invalidkeyexception) { invalidkeyexception.printStackTrace(); } catch (NoSuchAlgorithmException nosuchalgorithmexception) { nosuchalgorithmexception.printStackTrace(); } catch (NoSuchPaddingException nosuchpaddingexception) { nosuchpaddingexception.printStackTrace(); } LOGGER.error("Cipher creation failed!"); return null; }
public String decrypt(String str) { Cipher cipher; try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ips.getBytes("UTF-8"))); byte[] byteStr = Base64.decodeBase64(str.getBytes()); String Str = new String(cipher.doFinal(byteStr), "UTF-8"); return Str; } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) { } return null; }
public void runAll() throws InvalidKeyException, NoSuchPaddingException, InvalidAlgorithmParameterException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchProviderException { for (String mode : MODES) { for (String padding : PADDINGS) { if (!isMultipleKeyLengthSupported()) { runTest(mode, padding, minKeySize); } else { int keySize = maxKeySize; while (keySize >= minKeySize) { out.println("With Key Strength: " + keySize); runTest(mode, padding, keySize); keySize -= KEYCUTTER; } } } } }
public static String decrypt(String str) { if (str == null) return null; Cipher cipher; try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ips.getBytes("UTF-8"))); byte[] byteStr = Base64.decodeBase64(str.getBytes()); String Str = new String(cipher.doFinal(byteStr), "UTF-8"); return Str; } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
@BeforeClass public static void testProviderInstallationAtRuntime() throws NoSuchProviderException, NoSuchPaddingException { /* install wolfJCE provider at runtime */ Security.addProvider(new WolfCryptProvider()); Provider p = Security.getProvider("wolfJCE"); assertNotNull(p); /* populate enabledJCEAlgos to test */ for (int i = 0; i < supportedJCEAlgos.length; i++) { try { Cipher c = Cipher.getInstance(supportedJCEAlgos[i], "wolfJCE"); enabledJCEAlgos.add(supportedJCEAlgos[i]); } catch (NoSuchAlgorithmException e) { /* algorithm not enabled */ } } /* fill expected block size HashMap */ expectedBlockSizes.put("AES/CBC/NoPadding", 16); expectedBlockSizes.put("DESede/CBC/NoPadding", 8); expectedBlockSizes.put("RSA/ECB/PKCS1Padding", 0); }
/** * 加密方法 * * @param rawKeyData * @param str * @return * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws NoSuchPaddingException * @throws InvalidKeySpecException */ public static byte[] encrypt(byte rawKeyData[], String str) throws InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidKeySpecException { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); // 从原始密匙数据创建一个DESKeySpec对象 DESKeySpec dks = new DESKeySpec(rawKeyData); // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, key, sr); // 现在,获取数据并加密 byte data[] = str.getBytes(); // 正式执行加密操作 byte[] encryptedData = cipher.doFinal(data); System.out.println("加密后===>" + encryptedData); return encryptedData; }
public static MeviusTransferPacket getInstance(PublicKey publickey, MeviusPacket packet) throws MeviusCipherException { try { DESedeKeySpec desKeySpec = new DESedeKeySpec(((String) MeviusCipherKey.randomDESKey().getKey()).getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); Key key = keyFactory.generateSecret(desKeySpec); Cipher c = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "SunJCE"); c.init(Cipher.ENCRYPT_MODE, publickey); byte[] bkey = convertObj(key, c); c = Cipher.getInstance("DESede/ECB/PKCS5Padding"); c.init(Cipher.ENCRYPT_MODE, key); byte[] bobj = convertObj(packet, c); return new MeviusTransferPacket(bkey, bobj); } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | IOException | InvalidKeySpecException | IllegalBlockSizeException | BadPaddingException e) { e.printStackTrace(); throw new MeviusCipherException(e.getLocalizedMessage()); } }
private void wrapperPublicPriviteKeyTest(Provider p, String[] algorithms) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { for (String algo : algorithms) { // Key pair generated System.out.println("Generate key pair (algorithm: " + algo + ", provider: " + p.getName() + ")"); KeyPairGenerator kpg = KeyPairGenerator.getInstance(algo); kpg.initialize(512); KeyPair kp = kpg.genKeyPair(); // key generated String algoWrap = "DES"; KeyGenerator kg = KeyGenerator.getInstance(algoWrap, p); Key key = kg.generateKey(); wrapTest(algo, algoWrap, key, kp.getPrivate(), Cipher.PRIVATE_KEY, false); wrapTest(algo, algoWrap, key, kp.getPublic(), Cipher.PUBLIC_KEY, false); } }
@Override protected void engineSetPadding(String padding) throws NoSuchPaddingException { if ( ! mIsInited ) { NativeLib.init(); } if ( padding.length() == 0 ) { return; } if ( ! padding.equals("PKCS5Padding") ) { throw new NoSuchPaddingException("Only supports PKCS5Padding."); } mPadding = true; }
public Key getKey(PrivateKey privatekey) throws MeviusCipherException { try { Cipher c = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "SunJCE"); c.init(Cipher.DECRYPT_MODE, privatekey); /* * DESedeKeySpec desKeySpec = new DESedeKeySpec((byte[]) (convertByte(key, c))); * SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); return * keyFactory.generateSecret(desKeySpec); */ return (Key) convertByte(key, c); } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | ClassNotFoundException | IOException | IllegalBlockSizeException | BadPaddingException e) { e.printStackTrace(); throw new MeviusCipherException(e.getMessage()); } }
/** * this method is used to encrypt the password. * * @param value String password * @param encryption_key * @return encrypted password. * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws BadPaddingException * @throws IllegalBlockSizeException */ @SuppressWarnings("restriction") public static String encrypt(String value) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { encryption_key = getSalt(); Key key = generateKey(); Cipher c = Cipher.getInstance(ALGORITHM); c.init(Cipher.ENCRYPT_MODE, key); String valueToEnc = null; String eValue = value; for (int i = 0; i < ITERATIONS; i++) { valueToEnc = encryption_key + eValue; byte[] encValue = c.doFinal(valueToEnc.getBytes()); eValue = new sun.misc.BASE64Encoder().encode(encValue); } return eValue; }
public AESSensitivePropertyProvider(String keyHex) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException { byte[] key = validateKey(keyHex); try { Security.addProvider(new BouncyCastleProvider()); cipher = Cipher.getInstance(ALGORITHM, PROVIDER); // Only store the key if the cipher was initialized successfully this.key = new SecretKeySpec(key, "AES"); } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) { logger.error("Encountered an error initializing the {}: {}", IMPLEMENTATION_NAME, e.getMessage()); throw new SensitivePropertyProtectionException("Error initializing the protection cipher", e); } }
private byte[] decrypt(byte[] cipherText, byte[] key, byte[] initialVector) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance(cipherTransformation); SecretKeySpec secretKeySpecy = new SecretKeySpec(key, aesEncryptionAlgorithm); IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector); cipher.init(Cipher.DECRYPT_MODE, secretKeySpecy, ivParameterSpec); cipherText = cipher.doFinal(cipherText); return cipherText; }
public String encrypt(String plainText, String key) { String encodedString = ""; try { byte[] plainTextbytes = plainText.getBytes(characterEncoding); byte[] keyBytes = getKeyBytes(KEY_PREFIX + "" + key); encodedString = Base64.getEncoder().encodeToString(encrypt(plainTextbytes, keyBytes, keyBytes)); } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return encodedString; }
protected Cipher createCipher(int mode, String algorithm, String provider, Key key, AlgorithmParameters params) throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException, InvalidAlgorithmParameterException { Cipher cipher = null; if (cipherProvider == null) { cipher = Cipher.getInstance(algorithm); } else { cipher = Cipher.getInstance(algorithm, provider); } cipher.init(mode, key, params); return cipher; }
private String decrypt(String text) throws GeneralSecurityException { SecretKeySpec skeySpec = new SecretKeySpec( Base64.decodeBase64(ENCRYPTION_KEY), "AES"); byte[] result; try { byte[] decoded = Base64.decodeBase64(text.getBytes()); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); result = cipher.doFinal(decoded); } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) { throw new GeneralSecurityException( "unable to decrypt old encryption"); } return new String(result); }
/** * Returns an encrypted value from a given String value, encrypt/encode it * into an URL safe String. This method uses AES algorithm for encryption * and Apache Base64 class to encode it into URL safe String from byte * array. * * @param key --- This key is a 16byte String parameter. In ECAS it is * created using Apache RandomUtils method and is stored in the session. So * the key will be different for each session. * @param initVector --- This initVector is a 16byte String parameter. In * ECAS it is a constant that is maintained in each controller. * @param value --- This is the input value that will be encrypted. * @return * @throws Exception */ public String encrypt(String key, String initVector, String value) throws Exception { log.debug("Inside the encrypt method of EncryptDecryptService"); try { IvParameterSpec iv = new IvParameterSpec(initVector.getBytes(ENCODING)); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM_AES); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(value.getBytes()); log.info("Encrypted string: " + Base64.encodeBase64URLSafeString(encrypted)); return Base64.encodeBase64URLSafeString(encrypted); } catch (UnsupportedEncodingException | InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException ex) { log.error("Error while encryption: " + ex); throw ex; } }
/** * Returns a decrypted String value for a given encrypted value. This method * uses AES algorithm for encryption/decryption and Apache Commons Codec * Base64 class to decode it into a byte array. * * @param key--- This key is a 16byte String parameter. In ECAS it is * created using Apache RandomUtils method and is stored in the session. So * the key will be different for each session. * @param initVector --- This initVector is a 16byte String parameter. In * ECAS it is a constant that is maintained in each controller. * @param encrypted --- This is the encrypted value that will be decrypted. * @return * @throws Exception */ public String decrypt(String key, String initVector, String encrypted) throws Exception { try { IvParameterSpec iv = new IvParameterSpec(initVector.getBytes(ENCODING)); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM_AES); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted)); log.info("Decrypted string: " + original); return new String(original); } catch (UnsupportedEncodingException | InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException ex) { log.error("Error while decryption: " + ex); throw ex; } }
public static String decrypt(String encrypted) throws IllegalArgumentException, UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { IvParameterSpec iv = new IvParameterSpec(getInitVector()); SecretKeySpec skeySpec = new SecretKeySpec(getKey(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted.trim())); return new String(original); }
@NotNull private String getPublicKey() { if (publicKey == null || publicKey.isEmpty()) { final Context context = assetReceiveView.getContext(); try { publicKey = KeyPair.getKeyPair(context).publicKey; } catch (NoSuchPaddingException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | InvalidKeyException | IOException e) { Log.e(TAG, "getKeyPair: ", e); assetReceiveView.showError(ErrorMessageFactory.create(context, e), e); return ""; } } return publicKey; }
private Encryptor(String algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException { keyGen = KeyGenerator.getInstance(algorithm); key = keyGen.generateKey(); cipher = Cipher.getInstance(algorithm); }
CipherGenerator(String algo) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, NoSuchPaddingException, InvalidKeySpecException { // Do initialization byte[] salt = TestUtilities.generateBytes(IV_LENGTH); int iterCnt = 6; SecretKeyFactory skf = SecretKeyFactory.getInstance(algo.split("/")[0]); SecretKey key = skf .generateSecret(new PBEKeySpec(PASSWD.toCharArray())); AlgorithmParameterSpec aps = new PBEParameterSpec(salt, iterCnt); initCiphers(algo, key, aps); }
@Test public void test() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Encryptor encryptor = Encryptor.getInstance(Encryptor.ALG_DES); String plainText = "123456"; String encryptText = encryptor.encryptStr(plainText); System.out.println("plainText : " + plainText); System.out.println("encryptText : " + encryptText); String decryptText = encryptor.decryptStr(encryptText); System.out.println("decryptText : " + decryptText); }
public StudyPlanner(Account newAccount) throws NoSuchPaddingException, NoSuchAlgorithmException { this.account = newAccount; // Add Default Quantity types: Collections.addAll(this.quantityTypes, QuantityType.listOfQuantityTypes()); // Add Default Task types: Collections.addAll(this.taskTypes, TaskType.listOfTaskTypes()); }
@Test public void setGetPasswordLegacy() throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException, InvalidKeySpecException { Context context = InstrumentationRegistry.getTargetContext(); PasswordManager.setPasswordLegacy("myaddress", "mypassword", context); assertThat(PasswordManager.getPassword("myaddress", context), is("mypassword")); }
public static String encryptAES256PKCS5Padding(String key, String src) throws NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException { Cipher cipher = Cipher.getInstance(ALGORITHM_ENCODING); cipher.init(Cipher.ENCRYPT_MODE, generateKeyAES256(key), new IvParameterSpec(new byte[cipher.getBlockSize()])); return Base64.encodeBytes(cipher.doFinal(src.getBytes())); }
public static String decryptAES256PKCS5Padding(String key, String src) throws NoSuchPaddingException, NoSuchAlgorithmException, IOException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { Cipher cipher = Cipher.getInstance(ALGORITHM_ENCODING); cipher.init(Cipher.DECRYPT_MODE, generateKeyAES256(key), new IvParameterSpec(new byte[cipher.getBlockSize()])); return new String(cipher.doFinal(Base64.decode(src))); }
public static String encryptAES128PKCS7Padding(String key, String src) throws NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException { Cipher cipher = Cipher.getInstance(ALGORITHM_ENCODING); cipher.init(Cipher.ENCRYPT_MODE, generateKeyAES128(key), new IvParameterSpec(new byte[cipher.getBlockSize()])); return Base64.encodeBytes(cipher.doFinal(src.getBytes())); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exported); Log.d("redis", "Initialising jedis..."); Jedis jedis = new Jedis("localhost"); try { Cipher.getInstance("DES/ECB/ZeroBytePadding", "BC"); } catch (NoSuchAlgorithmException|NoSuchProviderException|NoSuchPaddingException e) { // pass } }
@Test public void isEmptyIsCorrect() throws NoSuchPaddingException, IOException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException { SecureString secureString1 = new SecureString(KEY, ""); assertTrue(secureString1.isEmpty()); }
private void wrapperBlowfishKeyTest() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { // how many kinds of padding mode int padKinds; // Keysize should be multiple of 8 bytes. int KeyCutter = 8; int kSize = BLOWFISH_MIN_KEYSIZE; String algorithm = "Blowfish"; int maxAllowKeyLength = Cipher.getMaxAllowedKeyLength(algorithm); boolean unLimitPolicy = maxAllowKeyLength == Integer.MAX_VALUE; SecretKey key = null; while (kSize <= BLOWFISH_MAX_KEYSIZE) { for (String mode : MODEL_AR) { // PKCS5padding is meaningful only for ECB, CBC, PCBC if (mode.equalsIgnoreCase(MODEL_AR[0]) || mode.equalsIgnoreCase(MODEL_AR[1]) || mode.equalsIgnoreCase(MODEL_AR[2])) { padKinds = PADDING_AR.length; } else { padKinds = 1; } // Initialization KeyGenerator kg = KeyGenerator.getInstance(algorithm); for (int k = 0; k < padKinds; k++) { String transformation = algorithm + "/" + mode + "/" + PADDING_AR[k]; if (NOPADDING.equals(PADDING_AR[k]) && kSize % 64 != 0) { out.println(transformation + " will not run if input length not multiple" + " of 8 bytes when padding is " + NOPADDING); continue; } kg.init(kSize); key = kg.generateKey(); // only run the tests on longer key lengths if unlimited // version of JCE jurisdiction policy files are installed if (!unLimitPolicy && kSize > LINIMITED_KEYSIZE) { out.println("keyStrength > 128 within " + algorithm + " will not run under global policy"); } else { wrapTest(transformation, transformation, key, key, Cipher.SECRET_KEY, false); } } } if (kSize <= LINIMITED_KEYSIZE) { KeyCutter = 8; } else { KeyCutter = 48; } kSize += KeyCutter; } }
/** * should never be called. */ protected void engineSetPadding( String padding) throws NoSuchPaddingException { if (!padding.equalsIgnoreCase("NoPadding")) { throw new NoSuchPaddingException("Padding " + padding + " unknown."); } }
/** * Construct a Cipher object */ private Cipher constructCipher(String algorithm, String digestAlgorithm) throws XMLEncryptionException { String jceAlgorithm = JCEMapper.translateURItoJCEID(algorithm); if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm); } Cipher c; try { if (requestedJCEProvider == null) { c = Cipher.getInstance(jceAlgorithm); } else { c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider); } } catch (NoSuchAlgorithmException nsae) { // Check to see if an RSA OAEP MGF-1 with SHA-1 algorithm was requested // Some JDKs don't support RSA/ECB/OAEPPadding if (XMLCipher.RSA_OAEP.equals(algorithm) && (digestAlgorithm == null || MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1.equals(digestAlgorithm))) { try { if (requestedJCEProvider == null) { c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding"); } else { c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", requestedJCEProvider); } } catch (Exception ex) { throw new XMLEncryptionException("empty", ex); } } else { throw new XMLEncryptionException("empty", nsae); } } catch (NoSuchProviderException nspre) { throw new XMLEncryptionException("empty", nspre); } catch (NoSuchPaddingException nspae) { throw new XMLEncryptionException("empty", nspae); } return c; }
public PBKDF2(String algo, String passwd) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException { super(algo, PBKDF2_SALT_SIZE); ci = Cipher.getInstance(CIPHER_TRANSFORMATION); PBEKeySpec pbeKeySpec = new PBEKeySpec(passwd.toCharArray(), getSalt(), ITERATION_COUNT, CIPHER_KEY_SIZE); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo); key = keyFactory.generateSecret(pbeKeySpec); }
/** * The private key corresponding to the contract certificate is to be decrypted by * the receiver (EVCC) using the session key derived in the ECDH protocol. * Applies the algorithm AES-CBC-128 according to NIST Special Publication 800-38A. * The initialization vector IV shall be read from the 16 most significant bytes of the * ContractSignatureEncryptedPrivateKey field. * * @param sessionKey The symmetric session key with which the encrypted private key is to be decrypted * @param encryptedKeyWithIV The encrypted private key of the contract certificate given as a byte array * whose first 16 byte hold the initialization vector * @return The decrypted private key of the contract certificate */ private static ECPrivateKey decryptPrivateKey(SecretKey sessionKey, byte[] encryptedKeyWithIV) { byte[] initVector = new byte[16]; byte[] encryptedKey = null; try { // Get the first 16 bytes of the encrypted private key which hold the IV encryptedKey = new byte[encryptedKeyWithIV.length - 16]; System.arraycopy(encryptedKeyWithIV, 0, initVector, 0, 16); System.arraycopy(encryptedKeyWithIV, 16, encryptedKey, 0, encryptedKeyWithIV.length - 16); IvParameterSpec ivParamSpec = new IvParameterSpec(initVector); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); /* * You must have the Java Cryptography Extension (JCE) Unlimited Strength * Jurisdiction Policy Files 8 installed, otherwise this cipher.init call will yield a * "java.security.InvalidKeyException: Illegal key size" */ cipher.init(Cipher.DECRYPT_MODE, sessionKey, ivParamSpec); byte[] decrypted = cipher.doFinal(encryptedKey); return getPrivateKey(decrypted); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | NegativeArraySizeException e) { getLogger().error(e.getClass().getSimpleName() + " occurred while trying to decrypt private key" + "\nSession key (" + (sessionKey != null ? sessionKey.getEncoded().length : 0) + " bytes): " + ByteUtils.toHexString(sessionKey.getEncoded()) + "\nEncrypted key (" + (encryptedKey != null ? encryptedKey.length : 0) + " bytes): " + ByteUtils.toHexString(encryptedKey) + "\nEncrypted key with IV (" + (encryptedKeyWithIV != null ? encryptedKeyWithIV.length : 0) + " bytes): " + ByteUtils.toHexString(encryptedKey), e); } return null; }
private static byte[] encrypt(byte[] raw, byte[] clear) { try { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(clear); return encrypted; } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) { throw new RuntimeException(e.toString(), e); } }
private static byte[] decrypt(byte[] raw, byte[] encrypted) { try { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] decrypted = cipher.doFinal(encrypted); return decrypted; } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) { throw new RuntimeException(e.toString(), e); } }
public MeviusPacket getPacket(Key key) throws MeviusCipherException { try { Cipher c = Cipher.getInstance("DESede/ECB/PKCS5Padding"); c.init(Cipher.DECRYPT_MODE, key); return (MeviusPacket) convertByte(obj, c); } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | ClassNotFoundException | IOException | IllegalBlockSizeException | BadPaddingException e) { throw new MeviusCipherException(e.getMessage()); } }