001package co.codewizards.cloudstore.core.auth; 002 003import static co.codewizards.cloudstore.core.util.Util.*; 004 005import java.security.KeyFactory; 006import java.security.PrivateKey; 007import java.security.spec.EncodedKeySpec; 008import java.security.spec.PKCS8EncodedKeySpec; 009 010import javax.crypto.Cipher; 011import javax.crypto.spec.IvParameterSpec; 012import javax.crypto.spec.SecretKeySpec; 013 014public class SignedAuthTokenDecrypter { 015 private PrivateKey privateKey; 016 017 public SignedAuthTokenDecrypter(byte[] privateKeyData) { 018 assertNotNull("privateKeyData", privateKeyData); 019 BouncyCastleRegistrationUtil.registerBouncyCastleIfNeeded(); 020 try { 021 KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 022 EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyData); 023 this.privateKey = keyFactory.generatePrivate(privateKeySpec); 024 } catch (RuntimeException e) { 025 throw e; 026 } catch (Exception e) { 027 throw new RuntimeException(e); 028 } 029 } 030 031 public byte[] decrypt(EncryptedSignedAuthToken encryptedSignedAuthToken) { 032 assertNotNull("encryptedSignedAuthToken", encryptedSignedAuthToken); 033 assertNotNull("encryptedSignedAuthToken.encryptedSignedAuthTokenData", encryptedSignedAuthToken.getEncryptedSignedAuthTokenData()); 034 assertNotNull("encryptedSignedAuthToken.encryptedSymmetricKey", encryptedSignedAuthToken.getEncryptedSymmetricKey()); 035 try { 036 Cipher asymCipher = Cipher.getInstance("RSA/None/OAEPWITHSHA1ANDMGF1PADDING"); 037 asymCipher.init(Cipher.DECRYPT_MODE, privateKey); 038 byte[] symKey = asymCipher.doFinal(encryptedSignedAuthToken.getEncryptedSymmetricKey()); 039 040 Cipher symCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 041 symCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(symKey, "AES"), 042 new IvParameterSpec(encryptedSignedAuthToken.getEncryptedSignedAuthTokenDataIV())); 043 044 byte[] signedAuthTokenData = symCipher.doFinal(encryptedSignedAuthToken.getEncryptedSignedAuthTokenData()); 045 046 return signedAuthTokenData; 047 } catch (RuntimeException e) { 048 throw e; 049 } catch (Exception e) { 050 throw new RuntimeException(e); 051 } 052 } 053}