Java Code Examples for org.bouncycastle.util.encoders.Base64#encode()

The following examples show how to use org.bouncycastle.util.encoders.Base64#encode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RsaEncryption.java    From cstc with GNU General Public License v3.0 6 votes vote down vote up
protected byte[] perform(byte[] input) throws Exception {

		if( ! this.certAvailable.isSelected() )
			throw new IllegalArgumentException("No certificate available.");
		
		String padding = (String)paddings.getSelectedItem();
		Cipher cipher = Cipher.getInstance(String.format("%s/%s/%s", algorithm, cipherMode, padding));
        cipher.init(Cipher.ENCRYPT_MODE, this.cert.getPublicKey());
        
        String selectedInputMode = (String)inputMode.getSelectedItem();
        String selectedOutputMode = (String)outputMode.getSelectedItem();
        
        if( selectedInputMode.equals("Hex") )
        	input = Hex.decode(input);
        if( selectedInputMode.equals("Base64") )
        	input = Base64.decode(input);
      
		byte[] encrypted = cipher.doFinal(input);
		
		if( selectedOutputMode.equals("Hex") )
			encrypted = Hex.encode(encrypted);
		if( selectedOutputMode.equals("Base64") )
			encrypted = Base64.encode(encrypted);

		return encrypted;
	}
 
Example 2
Source File: RsaDecryption.java    From cstc with GNU General Public License v3.0 6 votes vote down vote up
protected byte[] perform(byte[] input) throws Exception {

		if( ! this.keyAvailable.isSelected() )
			throw new IllegalArgumentException("No private key available.");
		
		String padding = (String)paddings.getSelectedItem();
		Cipher cipher = Cipher.getInstance(String.format("%s/%s/%s", algorithm, cipherMode, padding));
        cipher.init(Cipher.DECRYPT_MODE, this.selectedEntry.getPrivateKey());
        
        String selectedInputMode = (String)inputMode.getSelectedItem();
        String selectedOutputMode = (String)outputMode.getSelectedItem();
        
        if( selectedInputMode.equals("Hex") )
        	input = Hex.decode(input);
        if( selectedInputMode.equals("Base64") )
        	input = Base64.decode(input);
      
		byte[] encrypted = cipher.doFinal(input);
		
		if( selectedOutputMode.equals("Hex") )
			encrypted = Hex.encode(encrypted);
		if( selectedOutputMode.equals("Base64") )
			encrypted = Base64.encode(encrypted);

		return encrypted;
	}
 
Example 3
Source File: SecurityUtils.java    From sctalk with Apache License 2.0 6 votes vote down vote up
/**
 * 加密
 * @param strMsg 明文
 * @return 加密后的byte数组(base64)
 * @since  1.0
 */
public byte[] EncryptMsg(String strMsg) {
    try {
        byte[] pInData = strMsg.getBytes("utf8");
        int nInLen = pInData.length;
        int nRemain = nInLen % 16;
        int nBlocks = (nInLen + 15) / 16;

        if (nRemain > 12 || nRemain == 0) {
            nBlocks += 1;
        }
        int nEncryptLen = nBlocks * 16;

        byte[] pData = Arrays.copyOf(pInData, nEncryptLen);

        byte[] lenbytes = CommonUtils.intToBytes(nInLen);

        for (int i = 0; i < 4; i++) {
            pData[nEncryptLen + i - 4] = lenbytes[i];
        }
        byte[] encrypted = AESUtils.encrypt(pData);
        return Base64.encode(encrypted);
    } catch (UnsupportedEncodingException e) {
        return new byte[]{};
    }
}
 
Example 4
Source File: EncryptionUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * queueEncrypt / queueDecryt works only for marshaled object.
 *
 * @param data
 * @param publicKey
 * @return
 * @throws IntegrationModuleException
 */
public byte[] queueEncrypt(byte[] data, PublicKey publicKey) throws IntegrationModuleException {

    String s = new String(data);
    s += encryptionSignature;
    data = s.getBytes();
    try {
        String key = publicKey.toString().substring(0, 16);
        final SecretKeySpec symKey = new SecretKeySpec(key.getBytes(), "AES");

        Cipher cipher = Cipher.getInstance("AES");

        int rest = 0;
        int length = 0;
        byte[] newbuf = null;

        if (cipher.getBlockSize() > 0) {
            rest = data.length % cipher.getBlockSize();
            length = data.length + (cipher.getBlockSize() - rest);

            newbuf = new byte[length];
            System.arraycopy(data, 0, newbuf, 0, data.length);
        } else {
            newbuf = new byte[data.length];
            System.arraycopy(data, 0, newbuf, 0, data.length);
        }

        cipher.init(Cipher.ENCRYPT_MODE, symKey);
        byte[] cipherData = cipher.doFinal(newbuf);

        return Base64.encode(cipherData);
    } catch (Throwable t) {
        Exceptionutils.errorHandler(t);
    }
    return null;
}
 
Example 5
Source File: CryptOperation.java    From cstc with GNU General Public License v3.0 5 votes vote down vote up
protected byte[] crypt(byte[] input, int cipherMode, String algorithm, String mode, String padding)
		throws Exception {
	byte[] key = keyTxt.getText();
	byte[] iv = ivTxt.getText();

	SecretKeySpec secretKeySpec = new SecretKeySpec(key, algorithm);
	IvParameterSpec ivSpec = new IvParameterSpec(iv);
	Cipher cipher = Cipher.getInstance(String.format("%s/%s/%s", algorithm, mode, padding));

       if( mode.equals("ECB") ) {
           cipher.init(cipherMode, secretKeySpec);
       } else {
           cipher.init(cipherMode, secretKeySpec, ivSpec);
       }

       String selectedInputMode = (String)inputMode.getSelectedItem();
       String selectedOutputMode = (String)outputMode.getSelectedItem();
       
       if( selectedInputMode.equals("Hex") )
       	input = Hex.decode(input);
       if( selectedInputMode.equals("Base64") )
       	input = Base64.decode(input);
     
	byte[] encrypted = cipher.doFinal(input);
	
	if( selectedOutputMode.equals("Hex") )
		encrypted = Hex.encode(encrypted);
	if( selectedOutputMode.equals("Base64") )
		encrypted = Base64.encode(encrypted);

	return encrypted;
}
 
Example 6
Source File: BuilderUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void checkHash(byte[] blobHashValue, byte[] decompressedBlob) throws InvalidBlobContentConnectorException, TechnicalConnectorException {
   try {
      byte[] calculatedHashValue = buildHash(decompressedBlob);
      if (!Arrays.areEqual(blobHashValue, calculatedHashValue)) {
         String blobHashAsString = blobHashValue != null ? new String(Base64.encode(blobHashValue)) : "";
         String calculatedHashAsString = calculatedHashValue != null ? new String(Base64.encode(calculatedHashValue)) : "";
         throw new InvalidBlobContentConnectorException(InvalidBlobContentConnectorExceptionValues.HASH_VALUES_DIFFERENT, (Blob)null, decompressedBlob, new Object[]{blobHashAsString, calculatedHashAsString});
      }
   } catch (NoSuchAlgorithmException var5) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example 7
Source File: LdapImportUsersCmd.java    From cosmic with Apache License 2.0 5 votes vote down vote up
private String generatePassword() throws ServerApiException {
    try {
        final SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG");
        final byte bytes[] = new byte[20];
        randomGen.nextBytes(bytes);
        return new String(Base64.encode(bytes), "UTF-8");
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to generate random password");
    }
}
 
Example 8
Source File: KgssServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public KeyResult getNewKey(GetNewKeyRequestContent request, byte[] kgssETK) throws TechnicalConnectorException {
   Credential encryptionCredential = Session.getInstance().getSession().getEncryptionCredential();
   Map<String, PrivateKey> decryptionKeys = Session.getInstance().getSession().getEncryptionPrivateKeys();
   GetNewKeyResponseContent response = this.getNewKey(request, encryptionCredential, decryptionKeys, kgssETK);
   byte[] keyResponse = response.getNewKey();
   String keyId = new String(Base64.encode(response.getNewKeyIdentifier()));
   return new KeyResult(new SecretKeySpec(keyResponse, "AES"), keyId);
}
 
Example 9
Source File: LdapCreateAccountCmd.java    From cosmic with Apache License 2.0 5 votes vote down vote up
private String generatePassword() throws ServerApiException {
    try {
        final SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG");
        final byte bytes[] = new byte[20];
        randomGen.nextBytes(bytes);
        return new String(Base64.encode(bytes), "UTF-8");
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to generate random password");
    }
}
 
Example 10
Source File: KgssServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public KeyResult getNewKey(GetNewKeyRequestContent request, UUID keystoreId, KeyStore keystore, String quality, String passPhrase, byte[] kgssETK) throws TechnicalConnectorException {
   Credential credential = new KeyStoreCredential(keystoreId, keystore, "authentication", passPhrase, quality);
   Map<String, PrivateKey> hokPrivateKeys = KeyManager.getDecryptionKeys(keystore, passPhrase.toCharArray());
   Crypto crypto = CryptoFactory.getCrypto(credential, hokPrivateKeys);

   GetNewKeyResponseContent response = this.getNewKey(request, crypto, credential, hokPrivateKeys, kgssETK);
   byte[] keyResponse = response.getNewKey();
   String keyId = new String(Base64.encode(response.getNewKeyIdentifier()));
   return new KeyResult(new SecretKeySpec(keyResponse, "AES"), keyId);
}
 
Example 11
Source File: BuilderUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void checkHash(byte[] blobHashValue, byte[] decompressedBlob) throws InvalidBlobContentConnectorException, TechnicalConnectorException {
   try {
      byte[] calculatedHashValue = buildHash(decompressedBlob);
      if (!Arrays.areEqual(blobHashValue, calculatedHashValue)) {
         String blobHashAsString = blobHashValue != null ? new String(Base64.encode(blobHashValue)) : "";
         String calculatedHashAsString = calculatedHashValue != null ? new String(Base64.encode(calculatedHashValue)) : "";
         throw new InvalidBlobContentConnectorException(InvalidBlobContentConnectorExceptionValues.HASH_VALUES_DIFFERENT, (Blob)null, decompressedBlob, new Object[]{blobHashAsString, calculatedHashAsString});
      }
   } catch (NoSuchAlgorithmException var5) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var5, new Object[]{var5.getMessage()});
   }
}
 
Example 12
Source File: SendMessageBuilderImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private String processDigest(byte[] data) throws TechnicalConnectorException {
   return new String(Base64.encode(ConnectorCryptoUtils.calculateDigest("SHA-256", data)));
}
 
Example 13
Source File: FolderEncryptor.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private static String sealFolders(Crypto crypto, String folders, String hubIdPropKey, String hubAppIdPropKey) throws TechnicalConnectorException, UnsupportedEncodingException {
   byte[] encryptedMessage = crypto.seal(Crypto.SigningPolicySelector.WITH_NON_REPUDIATION, getHubEtk(hubIdPropKey, hubAppIdPropKey), folders.getBytes(Charset.UTF_8.getName()));
   encryptedMessage = Base64.encode(encryptedMessage);
   return new String(encryptedMessage);
}
 
Example 14
Source File: FolderEncryptor.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private static String sealFolders(Crypto crypto, String folders, String hubIdPropKey, String hubAppIdPropKey) throws TechnicalConnectorException, UnsupportedEncodingException {
   byte[] encryptedMessage = crypto.seal(Crypto.SigningPolicySelector.WITH_NON_REPUDIATION, getHubEtk(hubIdPropKey, hubAppIdPropKey), folders.getBytes(Charset.UTF_8.getName()));
   encryptedMessage = Base64.encode(encryptedMessage);
   return new String(encryptedMessage);
}
 
Example 15
Source File: SendMessageBuilderImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private String processDigest(byte[] data) throws TechnicalConnectorException {
   return new String(Base64.encode(ConnectorCryptoUtils.calculateDigest("SHA-256", data)));
}
 
Example 16
Source File: FolderEncryptor.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private static String sealFolders(Crypto crypto, String folders) throws TechnicalConnectorException, UnsupportedEncodingException {
   byte[] encryptedMessage = crypto.seal(Crypto.SigningPolicySelector.WITH_NON_REPUDIATION, getHubEtk(), folders.getBytes(Charset.UTF_8.getName()));
   encryptedMessage = Base64.encode(encryptedMessage);
   return new String(encryptedMessage);
}
 
Example 17
Source File: FolderEncryptor.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private static String sealFolders(Crypto crypto, String folders, String hubIdPropKey, String hubAppIdPropKey) throws TechnicalConnectorException, UnsupportedEncodingException {
   byte[] encryptedMessage = crypto.seal(Crypto.SigningPolicySelector.WITH_NON_REPUDIATION, getHubEtk(hubIdPropKey, hubAppIdPropKey), folders.getBytes(Charset.UTF_8.getName()));
   encryptedMessage = Base64.encode(encryptedMessage);
   return new String(encryptedMessage);
}
 
Example 18
Source File: FolderEncryptor.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private static String sealFolders(Crypto crypto, String folders, Long hubId, String hubApplication, EncryptionToken hubEtk) throws TechnicalConnectorException, UnsupportedEncodingException {
   byte[] encryptedMessage = crypto.seal(Crypto.SigningPolicySelector.WITH_NON_REPUDIATION, hubEtk, folders.getBytes(Charset.UTF_8.getName()));
   encryptedMessage = Base64.encode(encryptedMessage);
   return new String(encryptedMessage);
}
 
Example 19
Source File: LittleTsaService.java    From littleca with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "tsa", method = RequestMethod.POST)
public void tsa(HttpServletRequest req, HttpServletResponse resp) {
    String remoteIp = req.getRemoteAddr();
    try {
        if (!TsaTranserConstant.TIMESTAMP_QUERY_CONTENT_TYPE.equalsIgnoreCase(req.getContentType())) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "content type should be " + TsaTranserConstant.TIMESTAMP_QUERY_CONTENT_TYPE);
            return;
        }
        if (!TsaTranserConstant.TIMESTAMP_QUERY_CONTENT_TYPE.equalsIgnoreCase(req.getContentType())) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "content type should be " + TsaTranserConstant.TIMESTAMP_QUERY_CONTENT_TYPE);
            return;
        }
        if (littleTsaConfig.isUsernameEnabled()) {
            if (!littleTsaConfig.getTsaUsername().equals(req.getHeader("username")) || !littleTsaConfig.getTsaPassword().equals(req.getHeader("password"))) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "username and password must match");
                return;
            }
        }
        if (req.getContentLength() == 0) {
            LOG.error("timestamp request is empty");
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "timestamp request is empty");
            return;
        }
        boolean isBase64 = TsaTranserConstant.isBase64(req.getHeader(TsaTranserConstant.TRANSFER_ENCODING_HEADER));
        TimeStampRequest timeStampRequest = readRequest(req, isBase64);

        LOG.debug("TS Request received from {}", remoteIp);
        TimeStampResponse stampResponse = timeStampService.timestamp(timeStampRequest);
        if (stampResponse == null) {
            LOG.warn("TS Request received from {} is not acceptable", remoteIp);
            resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Could not generate timestamp response");
            return;
        }
        if (stampResponse.getTimeStampToken() == null) {
            LOG.warn("TS Request received from {} is not acceptable", remoteIp);
            resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Could not generate timestamp response");
            return;
        }
        byte[] response = stampResponse.getEncoded();
        if (isBase64) {
            resp.setHeader(TsaTranserConstant.TRANSFER_ENCODING_HEADER, TsaTranserConstant.TRANSFER_ENCODING_BASE64);
            response = Base64.encode(response);
            LOG.debug("Responding to {} is in base64", remoteIp);
        } else {
            resp.setHeader(TsaTranserConstant.TRANSFER_ENCODING_HEADER, TsaTranserConstant.TRANSFER_ENCODING_BINARY);
            LOG.debug("Responding to %s is in binary mode", remoteIp);
        }

        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType(TsaTranserConstant.TIMESTAMP_REPLY_CONTENT_TYPE);
        resp.setContentLength(response.length);
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(response);
        outputStream.close();
    } catch (Exception e) {
        LOG.warn("TS Request received from {} is not acceptable", remoteIp);
        try {
            resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Could not generate timestamp response");
        } catch (IOException ex) {
            LOG.error("error,{}", ex);
        }
    }
}
 
Example 20
Source File: Base64Utils.java    From NetworkDisk_Storage with GNU General Public License v2.0 2 votes vote down vote up
/**
 * <p>
 * 二进制数据编码为BASE64字符串
 * </p>
 * 
 * @param bytes
 * @return
 * @throws Exception
 */
public static String encode(byte[] bytes) throws Exception {
    return new String(Base64.encode(bytes));
}