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

The following examples show how to use org.bouncycastle.util.encoders.Base64#toBase64String() . 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: KeyPairGenerate.java    From ofdrw with Apache License 2.0 6 votes vote down vote up
@Test
void gen() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    // 获取SM2椭圆曲线的参数
    final ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
    // 获取一个椭圆曲线类型的密钥对生成器
    final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
    // 使用SM2参数初始化生成器
    kpg.initialize(sm2Spec);

    // 使用SM2的算法区域初始化密钥生成器
    kpg.initialize(sm2Spec, new SecureRandom());
    // 获取密钥对
    KeyPair keyPair = kpg.generateKeyPair();

    PublicKey pubKey = keyPair.getPublic();
    String pubKEnc = Base64.toBase64String(pubKey.getEncoded());
    System.out.println(">> Pub Key: " + pubKEnc);

    PrivateKey priKey = keyPair.getPrivate();
    String priKEnc = Base64.toBase64String(priKey.getEncoded());
    System.out.println(">> Pri Key: " + priKEnc);
}
 
Example 2
Source File: ZipUTF8CryptoWriter.java    From fastods with GNU General Public License v3.0 6 votes vote down vote up
private EntryAndData getEncryptedEntryAndDataUnchecked(final byte[] plainTextBytes)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException,
        IllegalBlockSizeException {
    final byte[] salt = this.encrypter.generateSalt();
    final byte[] iv = this.encrypter.generateIV();
    final byte[] compressedTextBytes = this.encrypter.compress(plainTextBytes);
    final byte[] data = this.encrypter.encrypt(
            compressedTextBytes, salt, this.password, iv);
    final String compressedCheckSum = Base64.toBase64String(
            this.encrypter.getDataChecksum(compressedTextBytes));
    final long crc32 = this.getCrc32(data);
    final ManifestEntry entry = this.curEntry.encryptParameters(
            this.encrypter.buildParameters(
                    plainTextBytes.length, data.length, crc32, compressedCheckSum,
                    Base64.toBase64String(salt), Base64.toBase64String(iv)));
    return new EntryAndData(entry, data);
}
 
Example 3
Source File: LogSignatureVerifierTest.java    From certificate-transparency-java with Apache License 2.0 5 votes vote down vote up
@Test
public void signatureOnEmbeddedSCTsInFinalCertificateVerifies()
    throws IOException, CertificateEncodingException {
  // Flow:
  // github-chain.txt contains leaf certificate signed by issuing CA.
  // Leafcert contains three embedded SCTs, we verify them all
  List<Certificate> certsChain = new ArrayList<>();
  certsChain.addAll(loadCertificates(TEST_GITHUB_CHAIN));

  // the leaf cert is the first one in this test data
  X509Certificate leafcert = (X509Certificate) certsChain.get(0);
  Certificate issuerCert = certsChain.get(1);
  assertTrue(
      "The test certificate does have embedded SCTs", CertificateInfo.hasEmbeddedSCT(leafcert));
  List<Ct.SignedCertificateTimestamp> scts = VerifySignature.parseSCTsFromCert(leafcert);
  assertEquals("Expected 3 SCTs in the test certificate", 3, scts.size());
  Map<String, LogInfo> logInfos = getLogInfosGitHub();
  for (Ct.SignedCertificateTimestamp sct : scts) {
    String id = Base64.toBase64String(sct.getId().getKeyId().toByteArray());
    LogInfo logInfo = logInfos.get(id);
    System.out.println(id);
    LogSignatureVerifier verifier = new LogSignatureVerifier(logInfo);

    assertTrue(
        "Expected signature to verify OK",
        verifier.verifySCTOverPreCertificate(
            sct,
            leafcert,
            LogSignatureVerifier.issuerInformationFromCertificateIssuer(issuerCert)));
    assertTrue("Expected PreCertificate to verify OK", verifier.verifySignature(sct, certsChain));
  }
}
 
Example 4
Source File: cryptoCommon.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String calculateHash(String contentToEncode, String hash) {
    try {
        MessageDigest digest = MessageDigest.getInstance(hash);
        digest.update(contentToEncode.getBytes());
        return Base64.toBase64String(digest.digest());
    } catch (NoSuchAlgorithmException ex) {
        logp(Level.SEVERE, classname, "generateX509FromBytes", "CRYPTO-MSG-1000", printStackTrace(ex));
    }
    return null;
}
 
Example 5
Source File: GenericCryptoModule.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String hmacRequest(String password, String accesskey, String request) throws CryptoException {
    // Local variables
    Key sk = null;
    String keystoreurl;

    // Keystore location
    try {
        if ((keystoreurl = cryptoCommon.getConfigurationProperty("crypto.cfg.property.hmac.keystorelocation")) == null) {
            cryptoCommon.logp(Level.SEVERE, classname, "getHmacSignatureSigningKey", "CRYPTO-ERR-2505", "crypto.cfg.property.hmac.keystorelocation");
            throw new CryptoException(cryptoCommon.getMessageWithParam("CRYPTO-ERR-2505", "crypto.cfg.property.hmac.truststorelocation"));
        }
    } catch (java.util.MissingResourceException e) {
        cryptoCommon.logp(Level.SEVERE, classname, "getHmacSignatureSigningKey", "CRYPTO-ERR-2505", "crypto.cfg.property.hmac.keystorelocation");
        throw new CryptoException(cryptoCommon.getMessageWithParam("CRYPTO-ERR-2505", "crypto.cfg.property.hmac.truststorelocation"));
    }

    try {
        KeyStore keystore = KeyStore.getInstance("BCFKS", BC_FIPS_PROVIDER);
        keystore.load(new FileInputStream(keystoreurl), password.toCharArray());

        sk = keystore.getKey(accesskey, password.toCharArray());

    } catch (KeyStoreException | UnrecoverableEntryException | CertificateException | NoSuchAlgorithmException | IOException ex) {
        cryptoCommon.logp(Level.SEVERE, classname, "getHmacSignatureSigningKey", "CRYPTO-ERR-2506", ex.getLocalizedMessage());
        throw new CryptoException(cryptoCommon.getMessageWithParam("CRYPTO-ERR-2506", ex.getLocalizedMessage()));
    }
    if (sk == null) {
        cryptoCommon.logp(Level.SEVERE, classname, "getHmacSignatureVerificationKey", "CRYPTO-ERR-2508");
        throw new CryptoException(cryptoCommon.getMessageProperty("CRYPTO-ERR-2508"));
    }

    SecretKey key = (SecretKey) sk;

    return Base64.toBase64String(cryptoCommon.calculateHmac(key, request.getBytes(), "HmacSHA256"));
}
 
Example 6
Source File: common.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String calculateHMAC(String secret, String data) {
    try {
        SecretKeySpec signingKey = new SecretKeySpec(Hex.decode(secret), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleFipsProvider());
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(data.getBytes());
        return Base64.toBase64String(rawHmac);
    } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException ex) {
        System.out.println("Unexpected error while creating hash: " + ex.getMessage());
        throw new IllegalArgumentException();
    }
}
 
Example 7
Source File: LogSignatureVerifierTest.java    From certificate-transparency-java with Apache License 2.0 5 votes vote down vote up
/** Returns a Map of LogInfos with all log keys to verify the Github certificate */
private Map<String, LogInfo> getLogInfosGitHub() {
  Map<String, LogInfo> logInfos = new HashMap<>();
  LogInfo logInfo = LogInfo.fromKeyFile(TestData.fileName(TEST_LOG_KEY_PILOT));
  String id = Base64.toBase64String(logInfo.getID());
  logInfos.put(id, logInfo);
  logInfo = LogInfo.fromKeyFile(TestData.fileName(TEST_LOG_KEY_SKYDIVER));
  id = Base64.toBase64String(logInfo.getID());
  logInfos.put(id, logInfo);
  logInfo = LogInfo.fromKeyFile(TestData.fileName(TEST_LOG_KEY_DIGICERT));
  id = Base64.toBase64String(logInfo.getID());
  logInfos.put(id, logInfo);
  return logInfos;
}
 
Example 8
Source File: XMLSigner.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String getCertificateDigest(X509Certificate cert, String algorithm) throws Exception {
	try {
	MessageDigest md = MessageDigest.getInstance(algorithm);
	byte[] digestValue = md.digest(cert.getEncoded());
	return Base64.toBase64String(digestValue);
	}catch (Exception e) {
		throw new Exception("Erro ao gerar resumo do certificado");
	}
}
 
Example 9
Source File: common.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String calculateHMAC(String secret, String data) {
    try {
        SecretKeySpec signingKey = new SecretKeySpec(Hex.decode(secret), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleFipsProvider());
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(data.getBytes());
        return Base64.toBase64String(rawHmac);
    } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException ex) {
        System.out.println("Unexpected error while creating hash: " + ex.getMessage());
        throw new IllegalArgumentException();
    }
}
 
Example 10
Source File: DESCoder.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DESCoder aes = new DESCoder(CIPHER_DES_CBC_PKCS5PADDING);

    String msg = "Hello World!";
    System.out.println("原文: " + msg);
    byte[] encoded = aes.encrypt(msg.getBytes("UTF8"));
    String encodedBase64 = Base64.toBase64String(encoded);
    System.out.println("密文: " + encodedBase64);

    byte[] decodedBase64 = Base64.decode(encodedBase64);
    byte[] decoded = aes.decrypt(decodedBase64);
    System.out.println("明文: " + new String(decoded));
}
 
Example 11
Source File: AESCoder.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    AESCoder aes = new AESCoder(CIPHER_AES_CBC_PKCS5PADDING);

    String msg = "Hello World!";
    System.out.println("[AES加密、解密]");
    System.out.println("message: " + msg);
    byte[] encoded = aes.encrypt(msg.getBytes("UTF8"));
    String encodedBase64 = Base64.toBase64String(encoded);
    System.out.println("encoded: " + encodedBase64);

    byte[] decodedBase64 = Base64.decode(encodedBase64);
    byte[] decoded = aes.decrypt(decodedBase64);
    System.out.println("decoded: " + new String(decoded));
}
 
Example 12
Source File: B64.java    From jingtum-lib-java with MIT License 4 votes vote down vote up
public static String toString(byte[] bytes) {
	return Base64.toBase64String(bytes);
}
 
Example 13
Source File: VerifySignature.java    From certificate-transparency-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
  if (args.length < 3) {
    System.out.println(
        String.format(
            "Usage: %s <certificates chain> <sct> <log public key>",
            VerifySignature.class.getSimpleName()));
    System.out.println(
        "<sct> can be set to 'null' in which case embedded SCTs in the leaf certificate will be extracted and verified.");
    System.out.println(
        "<log public key> may point to a directory containing multiple public keys which will be matched agains the correct SCT to verify.");
    return;
  }

  String pemFile = args[0];
  String sctFile = args[1];
  String logPublicKeyFileorDir = args[2];

  List<Certificate> certs = CryptoDataLoader.certificatesFromFile(new File(pemFile));
  if (certs.isEmpty()) {
    System.out.println("ERROR: Certificates chain does not contain any certificates.");
    System.exit(-1);
  }
  byte[] sctBytes = null;
  List<Ct.SignedCertificateTimestamp> scts = new ArrayList<>();
  if ("null".equals(sctFile)) {
    System.out.println("No SCTs as input, assuming there are some in the cert");
    X509Certificate leafCert = (X509Certificate) certs.get(0);
    if (CertificateInfo.hasEmbeddedSCT(leafCert)) {
      // Get the SCT(s) from the certificate
      System.out.println("The leafcert does have some SCTs");
      scts = parseSCTsFromCert(leafCert);
    }
  } else {
    sctBytes = Files.toByteArray(new File(sctFile));
    try {
      scts.add(Ct.SignedCertificateTimestamp.parseFrom(sctBytes));
    } catch (InvalidProtocolBufferException e) {
      System.out.println("Not a protocol buffer. Trying reading as binary");
      scts.add(Deserializer.parseSCTFromBinary(new ByteArrayInputStream(sctBytes)));
    }
  }
  if (scts.isEmpty()) {
    System.out.println(
        "ERROR: Certificate does not contain SCTs, and no SCTs provided as input.");
    System.exit(-1);
  }

  // Read log keys
  Map<String, LogInfo> logInfos = readLogKeys(logPublicKeyFileorDir);

  // Verify the SCTs one at a time
  boolean success = true;
  for (Ct.SignedCertificateTimestamp sct : scts) {
    String id = Base64.toBase64String(sct.getId().getKeyId().toByteArray());
    System.out.println("SCT to verify with keyID: " + id);
    System.out.println(sct.toString());
    LogInfo logInfo = logInfos.get(id);
    if (logInfo == null) {
      System.out.println(
          "No log with ID: "
              + id
              + " found among loaded log keys, skipping verification with FAILURE");
      success = false;
    } else {
      LogSignatureVerifier verifier = new LogSignatureVerifier(logInfo);
      if (verifier.verifySignature(sct, certs)) {
        System.out.println("Signature verified OK.");
      } else {
        System.out.println("Signature verification FAILURE.");
        success = false;
      }
    }
  }
  if (!success) {
    System.exit(-1);
  }
}
 
Example 14
Source File: HexTest.java    From nuls-v2 with MIT License 4 votes vote down vote up
@Test
    public void testHexs() throws IOException, DecoderException {
        TranList list = new TranList();
        for (int i = 0; i < 100000; i++) {
            Transaction tx = buildTransaction();
            list.getTxs().add(tx);
        }
        byte[] bytes = list.serialize();
        long time1 = System.currentTimeMillis();
        String hex0 = HexUtil.encode(bytes);
        byte[] bytes0 = HexUtil.decode(hex0);
        long time2 = System.currentTimeMillis();
        Log.info("{} time used - io.nuls.tools.crypto.HexUtil.encode && decode ===StringLenght= {}", (time2 - time1), hex0.length());

        String hex1 = Hex.toHexString(bytes);
        byte[] bytes1 = Hex.decode(hex1);
        long time3 = System.currentTimeMillis();
        Log.info("{} time used - org.spongycastle.util.encoders.Hex.encode && decode ===StringLenght= {}", (time3 - time2), hex1.length());


        String hex2 = org.apache.commons.codec.binary.Hex.encodeHexString(bytes);
        byte[] bytes2 = org.apache.commons.codec.binary.Hex.decodeHex(hex2.toCharArray());
        long time4 = System.currentTimeMillis();
        Log.info("{} time used - org.apache.commons.codec.binary.Hex.encode && decode ===StringLenght= {}", (time4 - time3), hex2.length());

        String base0 = RPCUtil.encode(bytes);
        byte[] bytes3 = RPCUtil.decode(base0);
        long time5 = System.currentTimeMillis();
        Log.info("{} time used - java.util.Base64.encode && decode ===StringLenght= {}", (time5 - time4), base0.length());

        String base1 = Base64.toBase64String(bytes);
        byte[] bytes5 = Base64.decode(base1);
        long time6 = System.currentTimeMillis();
        Log.info("{} time used - org.spongycastle.util.encoders.Base64.encode && decode ===StringLenght= {}", (time6 - time5), base1.length());

        String base2 = org.apache.commons.net.util.Base64.encodeBase64String(bytes);
        byte[] bytes6 = org.apache.commons.net.util.Base64.decodeBase64(base2);
        long time7 = System.currentTimeMillis();
        Log.info("{} time used - org.apache.commons.net.util.Base64.encode && decode ===StringLenght= {}", (time7 - time6), base2.length());

//        String base3 = org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);
//        byte[] bytes7 = org.apache.commons.codec.binary.Base64.decodeBase64(base3);
//        long time8 = System.currentTimeMillis();
//        Log.info("{} time used - org.apache.commons.codec.binary.Base64.encode && decode ===StringLenght= {}", (time8 - time7), base3.length());

    }
 
Example 15
Source File: common.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static String calculateSha256(String contentToEncode) throws NoSuchAlgorithmException {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    digest.update(contentToEncode.getBytes());
    return Base64.toBase64String(digest.digest());
}
 
Example 16
Source File: common.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static String calculateSha256(String contentToEncode) throws NoSuchAlgorithmException {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    digest.update(contentToEncode.getBytes());
    return Base64.toBase64String(digest.digest());
}
 
Example 17
Source File: XMLSigner.java    From signer with GNU Lesser General Public License v3.0 2 votes vote down vote up
public Document sign(String fileNameSource) throws Throwable{
	
	Init.init();
	
	Document doc = buildXML(fileNameSource);
					
	if(keyStore == null) {
		new Throwable("Keystore nula");
	}
	
	if(alias == null)
		alias = "";
	
	X509Certificate cert = (X509Certificate) this.keyStore.getCertificate(alias);
	PrivateKey myPrKey = (PrivateKey) keyStore.getKey (alias, null);
	
	int numSignatures = doc.getElementsByTagName("ds:Signature").getLength() - 1;
	
	Element sigTag = (Element) doc.getElementsByTagName("ds:Signature").item(numSignatures);
	
	Element objectTag = signedObject(cert, doc);
	
	Init.init();
	Canonicalizer c14n = Canonicalizer.getInstance(CanonicalizationMethod.EXCLUSIVE);
	
	byte[] canonicalized = null;
	
	if(sigPack != SignaturePack.DETACHED){
		canonicalized = c14n.canonicalizeSubtree(objectTag.getElementsByTagName("xades:SignedProperties").item(0)); 
	}else {
		canonicalized = null;
	}
	
	Element sigRefTag = createSignatureHashReference(doc, canonicalized);
	doc.getElementsByTagName("ds:SignedInfo").item(numSignatures).appendChild(sigRefTag);
	
	c14n = Canonicalizer.getInstance(CanonicalizationMethod.INCLUSIVE);
	byte[] dh = c14n.canonicalizeSubtree(doc.getElementsByTagName("ds:SignedInfo").item(numSignatures));
	
	Signature sig = Signature.getInstance("SHA256withRSA");
	sig.initSign(myPrKey);
	sig.update(dh);
	byte[] s = sig.sign();
	
	Element signValueTag = doc.createElementNS(XMLNS, "ds:SignatureValue");
	signValueTag.setAttribute("Id", "value-"+id);
	String hash = Base64.toBase64String(s);
	String result = splitString(hash);
	
	signValueTag.setTextContent(result);
	sigTag.appendChild(signValueTag);
	
	
	Element keyInfo = doc.createElementNS(XMLNS, "ds:KeyInfo");
	doc.getElementsByTagName("ds:Signature").item(numSignatures).appendChild(keyInfo);
	
	Element x509 = doc.createElementNS(XMLNS, "ds:X509Data");
	keyInfo.appendChild(x509);
			
	Element x509Certificate = doc.createElementNS(XMLNS, "ds:X509Certificate");
	x509Certificate.setTextContent(splitString(Base64.toBase64String(cert.getEncoded())));
	x509.appendChild(x509Certificate );
	
	sigTag.appendChild(objectTag);
	
	signedDocument = doc;
	
	return doc;
}
 
Example 18
Source File: Utils.java    From aws-encryption-sdk-java with Apache License 2.0 2 votes vote down vote up
/**
 * Takes data in a byte array, encodes them in Base64, and returns the result as a String.
 *
 * @param data The data to encode.
 * @return Base64 string that encodes the {@code data}.
 */
public static String encodeBase64String(final byte[] data) {
    return Base64.toBase64String(data);
}
 
Example 19
Source File: Base64EncodingTextEncryptor.java    From flair-engine with Apache License 2.0 2 votes vote down vote up
/**
 * Encrypt the raw text string.
 *
 * @param text text
 */
@Override
public String encrypt(String text) {
    return Base64.toBase64String(bytesEncryptor.encrypt(Utf8.encode(text)));
}
 
Example 20
Source File: ByteUtil.java    From javasdk with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * encode bytes to base64 string.
 * @param data bytes
 * @return base64 string
 */
public static String base64(byte[] data) {
    return Base64.toBase64String(data);
}