电子凭证签名加密和解密


背景:

1、基于安全考虑,电子凭证在getOrderCodes接口返回的code进行了签名,但是码商必须依赖这个接口比对自己库中的码,是否核销,是否过期等来做下一步的业务决策,所以向码商提供加密和解密的算法的文档

demo:

public class TripleDes {
   private static final String Algorithm = "DESede/CBC/PKCS5Padding"; // 定义
   
   private static final String secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // 码商入驻给的密钥,如果遗忘了,请联系内部当时码商入驻接口人.
   
 
   /**
    * 加密
    * 
    * @param src
    *            需要加密的字符串
    * @param secret
    *            密钥,24字节
    */
   public static String encrypt(String src, String secret) {
      if (StringUtils.isEmpty(src) || StringUtils.isEmpty(secret)
            || secret.length() != 24) {
         return src;
      }
 
      try {
         // 生成密钥
         SecretKey deskey = new SecretKeySpec(secret.getBytes(), "DESede");
 
         // 加密
         Cipher c1 = Cipher.getInstance(Algorithm);
         IvParameterSpec iv = new IvParameterSpec(secret.substring(0, 8)
                .getBytes());
         c1.init(Cipher.ENCRYPT_MODE, deskey, iv);
         BASE64Encoder base64 = new BASE64Encoder();
         return base64.encode(c1.doFinal(src.getBytes()));
      } catch (java.security.NoSuchAlgorithmException e1) {
      } catch (javax.crypto.NoSuchPaddingException e2) {
      } catch (java.lang.Exception e3) {
      }
      return null;
   }
 
   /**
    * 解密
    * 
    * @param src
    *            需要解密的字符串
    * @param secret
    *            密钥,24字节
    */
   public static String decrypt(String src, String secret) {
      if (StringUtils.isEmpty(src) || StringUtils.isEmpty(secret)
            || secret.length() != 24) {
         return src;
      }
 
      try {
         // 生成密钥
         SecretKey deskey = new SecretKeySpec(secret.getBytes(), "DESede");
         Cipher c1 = Cipher.getInstance(Algorithm);
         IvParameterSpec iv = new IvParameterSpec(secret.substring(0, 8)
                .getBytes());
         c1.init(Cipher.DECRYPT_MODE, deskey, iv);
         BASE64Decoder base64 = new BASE64Decoder();
         return new String(c1.doFinal(base64.decodeBuffer(src)));
      } catch (java.security.NoSuchAlgorithmException e1) {
      } catch (javax.crypto.NoSuchPaddingException e2) {
      } catch (java.lang.Exception e3) {
      }
      return null;
   }
 
   public static void main(String[] args) {
      String code = "xxxxxxxxxxxxxxxxxxxxx";// 加密过的码
      String newSecret = secret.substring(0, 24);//加密串取前24位,这个请务必注意.
      System.out.println(new String(TripleDes.decrypt(code, newSecret)));// 解密
      System.out.println(new String(TripleDes.encrypt(
            TripleDes.decrypt(code, newSecret), newSecret))); // 加密
 
   }
}


FAQ

  • 关于此文档暂时还没有FAQ